Pthon logging Module Learning

logging module Basics

  • Simple printing of logs to screen
import logging 

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

//Screen Printing:
WARNING:root:This is warning message

By default, logging prints the log to the screen with a log level of WARNING: the log level size relationship is CARITICAL > ERROR > WARNING > INFO > DEBUG > NOTEST, or you can define the log level yourself.

  • Configure the output format and mode of logs through logging.basicConfig function
import  logging
logging.basicConfig(level = logging.DEBUG,
        format = '%(asctime)s %(filename)s[line:%(lineo)d] %(levelname)s %(message)s',
        datefmt = '%a,%d %b %Y %H:%M:%S',
        filename = 'myapp.log',
        filemode = 'w')
        
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

./myapp.log The contents of the file are:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning 
message

Parameters of logging.basicConfig function

Parameter Name Parameter Meaning
filename Specify log file name
filemode Same as the file function, specify how the log file will be opened'w'or'a'
format Specify the format and content of the output, which can output a lot of useful information
%(levelno)s Print log level values
%(levelname)s Print log level values
%(pathname)s Print the path to the current executor, which is sys.argv[0]
%(filename)s Print the name of the currently executing program
%(funcName)s Current function for printing logs
%(lineno)d Print the current line number of the log
%(asctime)s Current time for printing logs
%(thread)d Print Thread ID
%(threadName)s Print Thread Name
%(process)d Print process ID
%(message)s Print log information
datefmt Specify the time format, the same as time.strftime()
level Set the log level, defaulting to logging.WARNING
stream Specifies the output stream to log, can specify output to sys.stderr,sys.stdout, or file, default output to sys.stderr, stream is ignored when both stream and filename are specified

Several handle s for logging are as follows

Function Name Functional action
logging.StreamHandler Log output to stream, can be sys.stderr, sys.stdout, or file
logging.FileHandler Log output to file
logging.handlers.BaseRotatingHandler
logging.handlers.RotatingFileHandler
logging.handlers.TimedRotatingFileHandler
logging.handlers.SocketHandler Remote output log to TCP/IP sockets
logging.handlers.DatagramHandler Remote output log to UDP sockets
logging.handlers.SMTPHandler Remote Output Log to Mail Address
logging.handlers.SysLogHandler Log output to syslog
logging.handlers.NTEventLogHandler Remote Output Log to Event Log for Windows NT/2000/XP
logging.handlers.MemoryHandler Make buffer for log output to memory
logging.handlers.HTTPHandler Remote Output to HTTP Server via GET or POST

Because StreamHandler and FileHandler are common ways of handling logs, they are included directly in the logging module, while others are included in the logging.handlers module

logging module instance

  • Output log to both file and screen

import logging


logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='myapp.log',
                filemode='w')

#################################################################################################
#Define a StreamHandler,take INFO Level or higher log information is printed to standard errors and added to the current log processing object#
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
#################################################################################################

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
 
//On-screen printing:
root        : INFO     This is info message
root        : WARNING  This is warning message
./myapp.log The contents of the file are:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message
  • logging Log Rollback
import logging
from logging.handlers import RotatingFileHandler

#Define a Rotating FileHandler that backs up up up up to five log files, up to 10M per log file
Rthandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024,backupCount=5)
Rthandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler)

As you can see from the above example and this example, logging has a primary object for log processing, and all other processing is added through addHandler

  • Configuring logs through logging.config module
#logger.conf
###############################################
[loggers]
keys=root,example01,example02
[logger_root]
level=DEBUG
handlers=hand01,hand02
[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0
[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0
###############################################
[handlers]
keys=hand01,hand02,hand03
[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('myapp.log', 'a')
[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('myapp.log', 'a', 10*1024*1024, 5)
###############################################
[formatters]
keys=form01,form02
[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S
[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=
  • Example 1:
import logging
import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example01")

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
  • Example 2:
import logging
import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example02")

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')

Keywords: Windows

Added by sheila on Sun, 09 Jun 2019 23:12:27 +0300