Role:
The main record of information to make it easier to locate and view the problem.
The official website for the python logging module:
/zh-cn/3.7/library/#formatter-objects
Three methods of locating the problem:
debug debugging: once the code is written, there is no need to debug it, so the logger is introduced
() - generally used in test environments
Logger: When there is a problem in the production environment, you can check the logger to locate the problem.
Steps:
1. Initialize the log collector
2. Set the log collector level - the default is warning.
3. Initialize logging Processor - can be understood as a pen that writes logs
4. Setting the Log Processor Level
5. Add handler
6. Set the format of the log
7. Add a log processor
8. Set up different levels of logger
Here's the quote.
Log collector level
0. It's not written. Bullshit.
10 Use when debugging bugs in your program
20 Used during normal operation of the program
30 Warning, used when program does not run as expected
40 Program error
50 Serious issues
How to define the level: you can combine try: except: logging
The code implementation process is as follows:
```python import logging # Standard library, direct import. logger = ("Log name") # Initialize the log collector ("DEBUG") # Set the log collector level handler = ("Log Path") # Initialize log processor - file output (specify location using absolute path, defaults to current directory) ("warning") # Set the log processor level Default warning console_handler = () # Console output console_handler.setLevel("DEBUG") (handler) # Add handler (console_handler) # Set the log format, using colons in between is fine (module name - error line - collector name - level - message) fmt = ("%(filename)s-%(lineno)s-%(name)s-%(levelname)s-%(massage)s") (fmt) # Log Rotation - Adding a Log Processor # Set up different levels of loggers - just choose one level ("") ("") ("") ("") ("")
Issue 1: Level setting
For example, when set to debug, only those above or equal to this level will be printed.
For example, when you set it to warning, only ,critical will be printed.
It doesn't matter what the level of the (log collector) is, it's set to the level of the (log processor).
whichever is higher, choose the highest of the two if (log collector) is WARNING, (log processor)
If it's debug, take warning as the standard, and set both, so that you can add multiple handlers.
Issue 2: Instantiation
Instantiated directly in the module, if instantiated externally, it is easy to cause multiple log files to be generated
Question 3: Log format settings, python logging official website, find what you need to use.
/zh-cn/3.7/library/#formatter-objects
encapsulate as a class
import logging class LoggerHandler(): def __init__(self, name="root", level="DEBUG", file=None, format="%(filename)s:%(lineno)d:%(name)s:%(levelname)s:%(message)s" ): # Initialize the log collector logger = (name) # Set the collector level (level) # Inherits Logger and returns an instance of itself. # Initialize format, set format fmt = (format) # Initialize the processor # If file is empty, execute stream_handler, if it is, execute both. if file: file_handler = (file) # Set the handler level file_handler.setLevel(level) # Add handler (file_handler) # Add a log processor file_handler.setFormatter(fmt) stream_handler = () stream_handler.setLevel(level) (stream_handler) stream_handler.setFormatter(fmt) = logger def debug(self, msg): return (msg) def info(self,msg): return (msg) def warning(self,msg): return (msg) def error(self,msg): return (msg) def critical(self,msg): return (msg) # In order to ensure that each time is the same file, call the same logger object (to prevent the hand error write the wrong file name), so here directly initialize the logger this object is better # You can write the name, file parameters into the configuration file (here I wrote them directly into the configuration file, you can also pass them directly) logger = LoggerHandler(config.logger_name,,config.logger_file) # logger = LoggerHandler("python21",file="") if __name__ == '__main__': logger = LoggerHandler() ("world") # test.py:40:root:DEBUG:world - it should print on line 59, because the information is already saved in the logger -- it can be inherited directly!
Repackaging - after inheriting logger, found that you can directly locate which line to print, you can view the source code
import logging class LoggerHandler(): def __init__(self, name="root", level="DEBUG", file=None, format="%(filename)s:%(lineno)d:%(name)s:%(levelname)s:%(message)s" ): # logger(name) directly superinherits the name in logger. super().__init__(name) # Set the collector level # (level) (level) # Inherits Logger and returns an instance of itself. # Initialize format, set format fmt = (format) # Initialize the processor # If file is empty, execute stream_handler, if it is, execute both. if file: file_handler = (file) # Set the handler level file_handler.setLevel(level) # Add handler (file_handler) # Add a log processor file_handler.setFormatter(fmt) stream_handler = () stream_handler.setLevel(level) (stream_handler) stream_handler.setFormatter(fmt) # In order to ensure that each time is the same file, call the same logger object (to prevent the hand error write the wrong file name), so here directly initialize the logger this object is better # You can write the name, file parameters into the configuration file (here I wrote them directly into the configuration file, you can also pass them directly) logger = LoggerHandler(config.logger_name,,config.logger_file) # logger = LoggerHandler("python21",file="") if __name__ == '__main__': logger = LoggerHandler() ("world") # after inheritance --- test.py:44:root:DEBUG:world
Additional knowledge:python3 uses the logging package to write logs to the system's rsyslog
Recently I had to write a python program to write logs to rsyslog and save him to a specified file by configuring rsyslog's file.
First, I'd like to take a look at the common modules provided by logging:
logger: logger is mainly used to configure and send log messages. A logger object can be returned via (name).
Defaults to root if name is not specified.
A suitable name can be taken here.
The same name returns the same logger object. Use %(name)s in the Formatter method to print out this name in the log. for example:
log = ('mylog') log_format = ( 'hhl-%(name)s-server[%(process)d]-%(levelname)s: %(message)s') # Example of printed results: #Aug 2 12:44:41 [localhost] hhl-mylog-server[7409]-DEBUG: debug message handler:Send log records to destination,e.g. documents,socketet al. (and other authors)。This can be done here byaddHandlermethod to add multiplehandler,Enables hierarchical filtering of logs。If you want to send logs to thersyslogcenter,It is then possible to use theSysLogHandler(),You need to import him before using this method from import SysLogHandler This method has two parameters、one isrsyslogcenter的facility:Specified is the device to which it is sent,as ifkernel,mail,systemet al. (and other authors)et al. (and other authors),He also haslocal0-local7reserve。Here I uselocal5。There is also a parameter specifying thelogaddress of the program,existcentos7The default is/dev/log。示例as if下: log_hdlr=SysLogHandler(facility=SysLogHandler.LOG_LOCAL5, address='/dev/log') correspondingrsyslogSetup Files(/etc/): local5.* /var/log/ #Store all logs from local5 to file
If you want to filter log messages with handler, you can do so:
log_hdlr.setLevel() #This is where you specify that you want to receive error and higher level logs. formatter:Specify the output format of the log,Includes message format and date character format,for example: log_format = ( 'hhl-%(name)s-server[%(process)d]-%(levelname)s: %(message)s') # Output Example #Aug 2 12:44:41 [localhost] hhl-mylog-server[7409]-DEBUG: debug message
The formatter callable parameters are:
%(name)s Logger's name
%(levelname)s Log level in text form
%(message)s User-output messages
%(asctime)s The current time in string form. The default format is "2003-07-08 16:49:45,896". Commas followed by milliseconds
%(levelno)s log level in numeric form
%(pathname)s The full pathname of the module from which the logging output function was called, possibly without the
%(filename)s The filename of the module that calls the log output function
%(module)s The name of the module from which the log output function is called.
%(funcName)s Name of the function that calls the log output function
%(lineno)d Line of code where the statement calling the log output function is located
%(created)f The current time, expressed as a UNIX standard floating-point representation of time.
%(relativeCreated)d The number of milliseconds since the Logger was created when log messages are output.
%(thread)d thread ID. may not be available
%(threadName)s The thread name. There may be no
%(process)d Process ID. may not be available
From the above modules, I can realize the function I want!
Write logs to file ----- source code:
import logging from import SysLogHandler log = ('mylog') () log_hdlr=SysLogHandler(facility=SysLogHandler.LOG_LOCAL5, address='/dev/log') log_format = ( 'hhl-%(name)s-server[%(process)d]-%(levelname)s: %(message)s') log_hdlr.setFormatter(log_format) log_hdlr.setLevel()# Accepts error and above log messages (log_hdlr) ('debug message test')# Specify the level as debug ('error message test')# Specify the level as error #Lastly, only saveerrorand higher priority logs
I hope you can correct me if I may be wrong about something!
Above this python3 in the logging logging implementation process and encapsulated into a class operation is all I share with you, I hope to give you a reference, and I hope you support me more.