Python + logging output to screen, log log write to file

Source: Internet
Author: User
Tags log log remove filter

Original Address:https://www.cnblogs.com/nancyzhu/p/8551506.htmlLog

A log is a way to track events that occur when the software is running. The software developer calls the log function in the code to indicate that a particular event has occurred. an event is described by a descriptive message that can optionally contain variable data (that is, potentially different data for each occurrence of an event). events also have the importance of developers attributing events, and importance can also be called level or severity.

Logging provides a convenient set of functions for making simple logs. They are debug (), info (), warning (), error (), and Critical ().

The logging functions are named based on the level or severity of the events they are used to track. the standard level and its applicability are described below (in order of severity):

level when to use
DEBUG Details are generally only used when debugging problems.
INFO Prove that things work as expected.
WARNING Hints for unexpected events, or problems that may occur in the future. For example, there is not enough disk space. but the software will still run as usual.
ERROR Because of the more serious problem, the software has been unable to perform some functions.
CRITICAL A critical error indicates that the software cannot continue running.

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

The default level is that WARNING this means that only this level and above will feed back information unless the logging module is used to do other things.

Tracked events can be handled in different ways. The simplest way to do this is to print them out on the console. Another common method is to write to a disk file.

One, print to the console

Import logginglogging.debug (' Debug Info ') logging.warning (' Only this will output ... ') logging.info (' info info ')

Because the default setting is warning, all only warning information is output to the console.

Warning:root: Only this will output ...

Use Logging.basicconfig () to print information to the console

Import logginglogging.basicconfig (format= '% (asctime) s-% (pathname) s[line:% (Lineno) d]-% (levelname) s:% (message) s ',                    level=logging. Debug) logging.debug (' Debug Info ') logging.info (' info info ') logging.warning (' Warning info ') logging.error (' Error message ') Logging.critical (' critial information ')

Because the value of level in Logging.basicconfig () is set to logging. Debug, all debug, info, warning, error, critical log will print to the console.

Log level: Debug < Info < Warning < error < Criticallogging.debug (' debug level, lowest level, general developer used to print some debug information ') Logging.info (' Info level, normal output information, generally used to print some normal operation ') logging.warning (' waring level, generally used to print police information ') Logging.error (' Error level, generally used to print some error messages ') Logging.critical (' critical level, typically used to print some fatal error messages, highest rank ')

So if level = Logging.info () is set, the debug information is not output to the console.

Second, use Logging.basicconfig () to save log to file

Logging.basicconfig (level=logging. DEBUG, #控制台打印的日志级别                    filename= ' New.log ',                    filemode= ' A ', # #模式, W and a,w are write modes, each time the log is re-written, overwriting the previous log                    #a是追加模式, Default if not written, is the Append mode                    format=                    '% (asctime) s-% (pathname) s[line:% (Lineno) d]-% (levelname) s:% (message) s '                    # Log format                    )

If you set filename and FileMode in Logging.basicconfig (), only log to file will be saved and not output to the console.

Third, the previous screen input, also write to the file log

The logging library takes a modular design and provides many components: loggers, processors, filters, and formatters.

    • Logger exposes an interface that the application code can use directly.
    • Handler sends (logger-generated) log records to the appropriate destination.
    • Filter provides better granularity control, which determines which log records are output.
    • Formatter indicates the layout of the log records in the final output.

Loggers:

Logger object to do three things. First, they expose many methods to the application code so that the app can log messages at run time. Second, the Logger object determines which log messages need to be recorded by severity (the default filtering facility) or by the filter object. Third, the Logger object passes related log messages to all interested log processors.

The common methods of logger objects are divided into two categories: Configuring and sending messages.

These are the most common configuration methods:

Logger.setlevel () specifies the lowest security level log information that Logger will handle, debug is the lowest built-in security level, and critical is the highest build-in security level. For example, if the severity is info, the logger will only process info,warning,error and critical messages, and the debug message is ignored.
Logger.addhandler () and Logger.removehandler () Add and remove handler objects from the Logger object. The processor is described in handlers.
Logger.addfilter () and Logger.removefilter () Add and remove filter objects from the Logger object.

handlers

处理程序The object is responsible for assigning the appropriate log message (based on the severity of the log message) to the specified target of the handler. Logger An object can addHandler() add 0 or more handler objects by means of a method. For example, an application can send all log messages to a log file, all error levels (errors) and above log messages are sent to standard output, and all severity level (critical) log messages are sent to an e-mail address. in this example, three separate processors are required, each responsible for sending a specific level of messages to a specific location.

There are 4 kinds of commonly used:

1) logging. Streamhandler Console output


Using this handler, you can output information to any file object, such as Sys.stdout or Sys.stderr.

Its constructor is:
Streamhandler ([STRM])
Where the STRM parameter is a file object. Default is Sys.stderr


2) logging. Filehandler-File Output


Similar to Streamhandler, used to output log information to a file. But Filehandler will open this file for you. Its constructor is:
Filehandler (Filename[,mode])
FileName is a file name and you must specify a file name.
Mode is how the file is opened. The default is ' a ', which is added to the end of the file.


3) Logging.handlers.RotatingFileHandler , automatically split log files by size, regenerate files once the specified size is reached


This handler is similar to the filehandler above, but it can manage the file size. When the file reaches a certain size, it automatically renames the current log file and then creates a new log file with the same name to continue the output. For example, the log file is Chat.log. When the chat.log reaches the specified size, Rotatingfilehandler automatically renames the file to Chat.log.1. However, if chat.log.1 already exists, it will first rename chat.log.1 to chat.log.2 ... Finally, re-create the Chat.log and continue to output the log information. Its constructor is:
Rotatingfilehandler (filename[, mode[, maxbytes[, Backupcount]])
where filename and mode two parameters are the same as Filehandler.
The maxbytes is used to specify the maximum file size for the log file. If MaxBytes is 0, it means that the log file can be infinitely large, and the renaming process described above does not occur.
The backupcount is used to specify the number of reserved backup files. For example, if you specify 2, when the renaming process described above occurs, the original chat.log.2 is not renamed, but is deleted.


4) Logging.handlers.TimedRotatingFileHandler automatically split log files by Time


This handler is similar to Rotatingfilehandler, however, it does not determine when to recreate the log file by judging the size of the file, but instead automatically creates a new log file at a certain time interval. The process of renaming is similar to Rotatingfilehandler, but the new file is not an appended number but the current time. Its constructor is:
Timedrotatingfilehandler (filename [, when [, interval [, Backupcount]])
where the filename parameter and the Backupcount parameter and the Rotatingfilehandler have the same meaning.
Interval is the time interval.
The When parameter is a string. A unit that represents a time interval, not case-sensitive. It has the following values:
s S
M min
H hours
D Day
W per week (Interval==0 on behalf of Monday)
Midnight every morning

Configuration method:

    • setLevel()Method is the same as the log object, indicating the lowest level at which the log will be distributed. Why do you have two setLevel() methods? the level of the logger determines whether the message is to be passed to the processor. the level of each processor determines whether the message is to be distributed.
    • setFormatter()Select a formatter for the processor.
    • addFilter()and removeFilter() individually configure and de-Configure the filter objects on the handler.

Formatters

The formatter object sets the final rules, structure, and contents of the log information, the default time format is%y-%m-%d%h:%m:%s, and the following are some of the information commonly used by formatter

% (name) s

Logger's name.

% (Levelno) s

Log level in digital form

% (LevelName) s

Log level in text form

% (pathname) s

The full path name of the module that called the log output function may not have

% (filename) s

The file name of the module that called the log output function

% (module) s

Call the module name of the log output function

% (FuncName) s

Function name of the call log output function

% (Lineno) d

The line of code where the statement that called the log output function is located

% (created) f

Current time, represented by the UNIX standard floating-point number representing the time

% (relativecreated) d

The number of milliseconds since logger was created when the log information is output

% (Asctime) s

The current time in string form. The default format is "2003-07-08 16:49:45,896". The comma is followed by milliseconds

% (thread) d

The thread ID. Probably not.

% (ThreadName) s

The name of the thread. Probably not.

% (process) d

The process ID. Probably not.

% (message) s

User-Output messages

Demand:

Output log to the console and write logs to the log file.
Save 2 types of log, All.log save debug, info, warning, critical information, Error.log only save error information, and automatically split the log file by time.

Import loggingfrom Logging Import Handlersclass 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[li ne:% (Lineno) d]-% (levelname) s:% (message) s '): Self.logger = Logging.getlogger (filename) format_str = Loggin G.formatter (FMT) #设置日志格式 self.logger.setLevel (level) #设置日志级别 sh = logging. Streamhandler () #往屏幕上输出 sh.setformatter (format_str) #设置屏幕上显示的格式 th = handlers. Timedrotatingfilehandler (filename=filename,when=when,backupcount=backcount,encoding= ' utf-8 ') #往文件里写入 # Specifies the interval time automatically generates the file the processor #实例化TimedRotatingFileHandler #interval是时间间隔, Backupcount is the number of backup files, if more than this number, will be automatically deleted, when is the interval time sheet  BITS, units have the following types: # s seconds # M minute # H hours, # D days, # W per week (Interval==0 on behalf of Monday)      # Midnight every Morning 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 (' Warning ') log.logger.error (' Error ') log.logger.critical (' critical ') logger ( ' Error.log ', level= ' Error '). Logger.error (' ERROR ')

The results on the screen are as follows:

2018-03-13 21:06:46,092-d:/write_to_log.py[line:25]-debug:debug2018-03-13 21:06:46,092-d:/write_to_log.py[line : []-info:info2018-03-13 21:06:46,092-d:/write_to_log.py[line:27]-WARNING: Warning 2018-03-13 21:06:46,099-d:/write_to_ LOG.PY[LINE:28]-Error: Error 2018-03-13 21:06:46,099-d:/write_to_log.py[line:29]-CRITICAL: Critical 2018-03-13 21:06:46,100-d :/write_to_log.py[line:30]-Error:error

Because of When=d, the newly generated file name will take time, as shown below.

Python + logging output to screen, log log write to file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.