Python logging

Pythong logging module

img

syslog

Rsyslog

Python Logging

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# create a file handler
handler = logging.FileHandler('hello.log')
handler.setLevel(logging.INFO)

# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(handler)

logger.info('Hello baby')

Logger

logger names track the package/module hierarchy, and it’s intuitively obvious where events are logged just from the logger name.

Config

logging.ini

three ways:

Use rotating file handler

Level/ Severity

debug(), info(), warning(), error() and critical().

Handler

misc

TODO

  1. what is python module and __name__ variable? if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s name. A module’s __name__ is set equal to ‘__main__’ when read from standard input, a script, or from an interactive prompt. A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.