Python uses logging module outputs information to the screen and print the log to the specified file

Journal

Event log is a way of tracking what happens when the software is running. Software developers call log function in your code, indicating that a particular event occurred. Event is described by a descriptive message, the descriptive message may optionally contain variable data (i.e., for different events are potentially each occurrence data). The importance of the event also has a developer due to the event; also referred to the importance or severity level.

logging provides a convenient function to make simple log. They are debug (), info (), warning (), error () and critical ().

logging functions are named according to their severity level or to keep track of events. Standard levels and their applicability are described below (with the severity of the ascending order):

level When to Use
DEBUG For more information, generally used only when debugging problems.
INFO Prove things work as expected.
WARNING It prompted some unexpected events, or prompt problem may occur in the future. For example: insufficient disk space. But the software will still run as usual.
ERROR Due to more serious problems, the software can not perform some of the functions.
CRITICAL A serious error, indicating that the software can not continue to run.

 

level Numeric value
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0

The default level is WARNING, which means that only this level and above will feedback information unless logging module is used to do other things.

The events being tracked can be handled in different ways. The simplest approach is to print them out on the console. Another common method is written to a disk file.

First, printed to the console

Import logging 
logging.debug ( ' Debug Information ' ) 
logging.warning ( ' Only this will output ... ' ) 
logging.info ( ' info information ' )

Since the default setting is level warning, only warning that all information will be output to the console.

WARNING: root: this will only output. . .

Python uses logging module outputs information to the screen and print the log to the specified file

Use logging.basicConfig () print information to the console

import logging
logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                    level=logging.DEBUG)
logging.debug('debug 信息')
logging.info('info 信息')
logging.warning('warning 信息')
logging.error('error 信息')
logging.critical('critial 信息')

Since the set value of level () is in logging.basicConfig logging.DEBUG, all debug, info, warning, error, critical will print the log to the console.

Log Level: Debug <info <warning <error < Critical 
logging.debug ( ' Debug level, the lowest level, generally used by developers to print some debugging information ' ) 
logging.info ( ' info level, normal output, generally used to print some of the normal operation ' ) 
logging.warning ( ' Waring level, generally for printing alarm information ' ) 
logging.error ( ' error level, is generally used to print some error message ' ) 
logging.critical ( ' Critical level, generally used print some fatal error, the highest level ' )

Therefore, if the set level = logging.info (), then the information is not output to debug console.

Second, the use logging.basicConfig () to save the log file

logging.basicConfig (Level = logging.DEBUG, # log level of console print 
                    filename = ' new.log ' , 
                    the fileMode = ' A ' , # # mode, there w and a, w is the write mode, each time re-write log, prior to the override log 
                    # a is append mode, default if not write anything, the append mode 
                    the format = ' % (the asctime) S -% (pathname) S [Line:% (lineno) D] -% (levelname) S :% (Message) S ' # log format 
                    )
                    
                    

If () set the filename and filemode in logging.basicConfig, it will only save the log to a file, not output to the console.

Third, the previous screen input, but also to write log files

logging library taken modular design, provides a number of components: recorder, processor, and a formatter filter.

  • Logger exposed interface application code can be used directly.
  • The Handler (generated record) The log entry sent to the appropriate destination.
  • Filter provides better control of particle size, it may decide which logging output.
  • Formatter specified in the layout of the final output logging.

Loggers:

Logger objects do three things. First, they are exposed to a number of methods application code, so that the application message can be recorded at runtime. Second, the object to determine which records a log message needs to be recorded by severity (default filter facilities) or filter objects. Third, the object record log messages related transfer to all interested log handler.

Conventional method of recording object into two categories: Configuration and send messages.

These are the most common configuration methods:

Logger.setLevel () the lowest level of security log information specified logger will be processed, debug is the lowest level of built-in security, critical is the highest level of built-in security. For example, if the severity INFO, the recording process will only INFO, WARNING, ERROR and CRITICAL message, the DEBUG message is ignored.
Logger.addHandler () and Logger.removeHandler () handler object to add and remove objects from the recorder. Processor See Handlers.
Logger.addFilter () and Logger.removeFilter () to add and remove filters from the target object record.

Handlers

处理程序The object is responsible for the appropriate message log (log messages based on the severity of) assigned to the specified destination handler. Logger Objects can be addHandler()increased zero or more objects handler method. For example, an application can send all log messages to the log file, all error level (error) and above the log messages sent to standard output, all severity levels (critical) log messages to an electronic mailbox. In this example, it requires three separate processors, each responsible for sending a specific message to a specific level position.

There are four commonly used: 

1) logging.StreamHandler -> console output 


Handler can use this information to any output file object is similar to sys.stdout or sys.stderr of (file object).

Its constructor is:
The StreamHandler ([strm])
where strm parameter is a file object. The default is sys.stderr


2)   logging.FileHandler -> File Output


Similarly StreamHandler and for outputting information to a log file. But FileHandler will help you open the file. Its constructor is:
FileHandler (filename [, the MODE])
filename is the file name, you must specify a file name.
mode is to open the way to a file. The default is 'a', is added to the end of the file.


. 3)   logging.handlers.RotatingFileHandler -> log file according to the size of the automatic segmentation, once the specified file size is reached rebuild 


The Handler similar to the above FileHandler, but it can manage file size. When the file reaches a certain size, it will automatically rename the current log file, and then create a new log file of the same name continues to be output. For example, the log file is chat.log. When chat.log reaches the size specified, RotatingFileHandler files automatically renamed chat.log.1. However, if chat.log.1 already exists, it will first chat.log.1 rename chat.log.2. . . Finally, re-create chat.log, it continues to output log information. It is constructor:
RotatingFileHandler (filename [, mode [, MaxBytes [, BACKUPCOUNT]]])
where filename and mode parameters and two FileHandler same.
maxBytes file is used to specify the maximum log file size. If maxBytes is zero, this means that log files can be infinite, then renaming process described above does not occur.
backupCount for the specified number of backup files to keep. For example, if you specify 2, when the renaming process described above occurs, the original chat.log.2 will not be renamed, but was deleted.


. 4)   logging.handlers.TimedRotatingFileHandler ->  Automatic log file segmentation in time 


The Handler and RotatingFileHandler similar, but it does not have to decide when to re-create the log file to determine the file size, but a certain time interval automatically create a new log file. Renaming process and RotatingFileHandler similar, but the new files are not figures, but the current time. It is constructor:
TimedRotatingFileHandler (filename [, When [, interval The [, BACKUPCOUNT]]])
where filename BACKUPCOUNT parameters and parameters have the same meaning and RotatingFileHandler.
interval is the time interval.
when parameter is a string. Expressed in units of time intervals, a case-insensitive. It has the following values:
S seconds
M minutes
H h
D days
W per week (interval == 0 behalf Monday)
Midnight every morning

Configuration:

  • setLevel()The same method and the log object, indicating the lowest level would be distributed log. Why are there two setLevel()methods? Level recorder determines whether the message to be passed to the processor. Level of each processor determines whether the message is to be distributed.
  • setFormatter()For the processor selects a formatter.
  • addFilter()And removeFilter()are arranged on the object and the cancellation filter configuration handler.

Formatters

Formatter last rule set log information objects, structure and content, the default time format% Y-% m-% d% H:% M:% S, the following are some common information Formatter

%(name)s

Logger name

%(levelno)s

Log level in digital form

%(levelname)s

Text log level

%(pathname)s

The full path name of the call log output function module may not

%(filename)s

Call log output function module filename

%(module)s

Call log output function module name

%(funcName)s

Call log output function of the function name

%(lineno)d

Line statement calls log output function located

%(created)f

The current time, represented by the floating-point standard UNIX representing time

%(relativeCreated)d

Since Logger creation of a few milliseconds when the output log information

%(asctime)s

A string of the current time. The default format is "2003-07-0816: 49: 45,896." Milliseconds after the comma

%(thread)d

Thread ID. Maybe not

%(threadName)s

Thread name. Maybe not

%(process)d

Process ID. Maybe not

%(message)s

Message output to the user

 

 

demand:

Log output to the console and to write the log log file.
Save two types of log, all.log saved debug, info, warning, critical information, only the error.log stored error information, and automatically log file segmentation in time.

import logging
from logging import handlers

class Logger(object):
    level_relations = {
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warning':logging.WARNING,
        'error':logging.ERROR,
        'crit':logging.CRITICAL
    }#日志级别关系映射

    def __init__(self,filename,level='info',when='D',backCount=3,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)#设置日志格式
        self.logger.setLevel(self.level_relations.get(level))#设置日志级别
        sh = logging.StreamHandler()#往屏幕上输出
        sh.setFormatter(format_str) #设置屏幕上显示的格式
        th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')#往文件里写入#指定间隔时间自动生成文件的处理器
        #实例化TimedRotatingFileHandler
        #interval是时间间隔,backupCount是备份文件的个数,如果超过这个个数,就会自动删除,when是间隔的时间单位,单位有以下几种:
        # S 秒
        # M 分
        # H 小时、
        # D 天、
        # W 每星期(interval==0时代表星期一)
        # midnight 每天凌晨
        th.setFormatter(format_str)#设置文件里写入的格式
        self.logger.addHandler(sh) #把对象加到logger里
        self.logger.addHandler(th)
if __name__ == '__main__':
    log = Logger('all.log',level='debug')
    log.logger.debug('debug')
    log.logger.info('info')
    log.logger.warning('警告')
    log.logger.error('报错')
    log.logger.critical('严重')
    Logger('error.log', level='error').logger.error('error')

The results on the screen is as follows:

Python uses logging module outputs information to the screen and print the log to the specified file

Since when = D, will take time newly generated file name, as shown below.

Guess you like

Origin www.linuxidc.com/Linux/2019-06/158930.htm