Logging¶
Fonctionnalités de journalisation pour Python.
Exemples simples¶
Afficher les logs dans le terminal¶
import logging
logger = logging.getLogger(__name__)
def main() -> int:
logger.info("Hello World!")
return 0
if __name__ == "__main__":
# Log to sys.stderr:
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s :: %(name)s :: %(levelname)s :: %(message)s",
)
# Call main function:
import sys
sys.exit(main())
Enregistrer les logs dans un fichier¶
import logging
logger = logging.getLogger(__name__)
def main() -> int:
logger.info("Hello World!")
return 0
if __name__ == "__main__":
# Log to file:
logging.basicConfig(
level=logging.DEBUG,
filename="activity.log",
encoding="utf_8",
format="%(asctime)s :: %(name)s :: %(levelname)s :: %(message)s",
)
# Call main function:
import sys
sys.exit(main())
Combiner plusieurs gestionnaires de journalisation¶
Tip
Cet exemple utilise rich pour enrichir les messages d'erreur dans les logs.
import logging
logger = logging.getLogger(__name__)
def main() -> int:
logger.info("Hello World!")
return 0
if __name__ == "__main__":
# Log to file:
from logging import FileHandler, Formatter
file_formatter = Formatter(
"%(asctime)s :: %(name)s :: %(levelname)s :: %(message)s"
)
file_handler = FileHandler(
filename="activity.log",
encoding="utf_8",
)
file_handler.setFormatter(file_formatter)
file_handler.setLevel(logging.DEBUG)
# Log to sys.stderr with rich text:
from rich.logging import RichHandler
stream_formatter = Formatter("%(message)s")
stream_handler = RichHandler(rich_tracebacks=True)
stream_handler.setFormatter(stream_formatter)
stream_handler.setLevel(logging.DEBUG)
# Main logging configuration:
logging.basicConfig(
level=logging.NOTSET,
handlers=[
file_handler,
stream_handler,
],
)
# Call main function:
import sys
sys.exit(main())
Ressources¶
- Écrire des logs en Python — Sam & Max
- logging — Fonctionnalités de journalisation pour Python — Documentation Python 3
- Tutoriel sur la journalisation — Documentation Python 3
- Logging Cookbook — Documentation Python 3
- pygelf : Python logging handlers with GELF (Graylog Extended Log Format) support.