How to use Python's logging module

How to centrally manage the settings of the loggin module of python and output it in a consistent format with the date and time, the file name where the log was written, the log level (debug, info, error, ...), the output message, as shown below. Will be described.

2020-01-15 16:54:52,751 [logTest.py:9]INFO message.

Log settings

Manage format and log level in the logConf.py file.

utils/logConf.py


import logging

format="%(asctime)s [%(filename)s:%(lineno)d] %(levelname)-8s %(message)s"

logging.basicConfig(level=logging.DEBUG, format=format)

Log processing

A file that performs log processing

  1. Pass the path to logConf.py
  2. Set the logger in the file used by name

to hold. And you can log with logger.nfo or logger.error.

import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from utils.logConf import logging
logger = logging.getLogger(__name__)

logger.info("This is a message.")
logger.error("This is an error.")

"""
2020-01-15 16:54:52,751 [logTest.py:9]INFO message.
2020-01-15 16:54:52,751 [logTest.py:10]ERROR Error.
"""

Summary

With the above, simple logging process is possible. If you want to output a log file additionally, you can easily add additional functions by changing the logConf.py file.

Recommended Posts

How to use Python's logging module
How to use TouchDesigner Python's external module
How to use the optparse module
How to use the ConfigParser module
How to use Python's Context Manager
How to output additional information when logging with python's logging module
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to use shogun
How to use Pandas 2
How to use numpy.vectorize
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to use list []
How to use python-kabusapi
How to use OptParse
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
How to use Qt Designer
How to use search sorted
[gensim] How to use Doc2Vec
python3: How to use bottle (2)
How to use the generator
[Python] How to use list 1
How to use Python argparse
How to use IPython Notebook
How to use Pandas Rolling
[Note] How to use virtualenv
How to use redis-py Dictionaries
Python: How to use pydub
[Python] How to use checkio
[Go] How to use "... (3 periods)"
How to use Django's GeoIp2
[Python] How to use input ()
How to use the decorator
[Introduction] How to use open3d
How to use Python lambda
How to use Jupyter Notebook
[Python] How to use virtualenv
python3: How to use bottle (3)