Skip navigation

Tag Archives: tech

Python loggers are a good mechanism for printing to console or a log file when running any python file or especially useful when logging information from a server. Some of the useful things you can do are, logging to console and files at the same time, logging from different python packages, set logging filters to include timestamps and/or logging levels and/or handler information, and logging at different message levels weather an error is debug, information, a warning, an error, or critical level.

To create a logger:

import logging
LOG_FILENAME = 'mylog.log'
logging.debug('This message should go to the log file') #This is how to would print using the logger

or you can create a logger using:

LOG_FILENAME = 'mylog.log'

#Creating a logger
my_logger = logging.getLogger('MyLogger')

#Create handler - in this case a file handler
handler = logging.FileHandler(
LOG_FILENAME, mode='a')

#Set the format you want to log in
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

#add format to the logging handler

#add logging handler to logger

Note the mode=’a’ line means that this logging handler is going to append to the file. The mode ‘w’ means it will create a new file each time.

To add a console logger to our previous example so that we can see output on the console we would add the following code:

# create console handler and set level to debug
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG) #sets default default level to debug

# create formatter -- this is format only prints the level of the debug message
formatter = logging.Formatter("%(levelname)s - %(message)s")

# add formatter to console_handler

# add console_handler to logger

Now we have a console logger. Whenever we call:

my_logger.debug("this is a debug level message")

This will be printed to the console, and the log file at the debug level, each in different formats. Note that in this example, we changed the format from the original File Handler so that it only prints the logging level to the console handler.

This example from shows the debug level:

import logging
import logging.config


# create logger
logger = logging.getLogger("simpleExample")

# "application" code
logger.debug("debug message")"info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

And this one is how to handle each logging in each package:

import logging


logger1 = logging.getLogger('package1.module1')
logger2 = logging.getLogger('package2.module2')

logger1.warning('This message comes from one module')
logger2.warning('And this message comes from another module')