SoFunction
Updated on 2024-11-17

Python+logging output to screen writes logs to file

log (computing)

Logging is a method of tracking events that occur while software is running. Software developers call logging functions in their code to indicate that a particular event has occurred. Events are described by descriptive messages that may optionally contain variable data (i.e., data that is potentially different for each occurrence of the event). The event also has an importance attributed to it by the developer; importance can also be referred to as level or severity.

logging provides a convenient set of functions for simple logging. They are debug(), info(), warning(), error(), and critical().

The logging functions are named according to the level or severity of the events they are used to track. The standard levels and their applicability are described below (in increasing order of severity):

(military) rank When to use
DEBUG Detailed information, generally used only when debugging a problem.
INFO Proof that things work as expected.
WARNING Hints of certain unanticipated events, or hints of problems that may arise in the future. For example: insufficient disk space. But the software will run as usual.
ERROR Due to more serious problems, the software can no longer perform some functions.
CRITICAL A critical error indicates that the software can no longer continue to run.

(military) rank numerical 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 feed back information unless the logging module is being used for something else.

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

I. Print to Console

import logging
('debug info')
('Only this will output...')
('info info')

Since the default set level is warning, all only warning messages are output to the console.

WARNING:root: only this will output.

Print messages to the console using ()

import logging
(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
   level=)
('debug info')
('info info')
('warning message')
('error message')
('Critical information')

Since the value of level in () is set to, all debug, info, warning, error, critical logs are printed to the console.

Log level: debug < info < warning < error < critical
('debug level, the lowest level, generally used by developers to print some debugging information')
('info level, normal output information, generally used to print some normal operations')
('Waring level, generally used to print alert messages')
('error level, generally used to print some error messages')
('critical level, generally used to print some fatal error messages, the highest level')

So if you set level = (), debug messages will not be output to the console.

Second, the use of () to save the log to the file

(level=,The level of logs printed by the # console
   filename='',
   filemode='a',## Mode with w and a. w is the write mode, which rewrites the log each time, overwriting the previous logs
   #a is the append mode, by default if not written
   format=
   '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
   # Log format
   )

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

Third, both to the screen input, but also to the file to write the log

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

  • Logger exposes an interface that can be used directly by application code.
  • Handler sends the log records (generated by the logger) to the appropriate destination.
  • Filter provides better granularity control by deciding which log records to output.
  • Formatter specifies the layout of the log records in the final output.

Loggers:

Logger objects do three things. First, they expose a number of methods to the application code so that the application can log messages at runtime. Second, the Logger object determines which log messages need to be logged, either by severity (the default filtering facility) or by filter objects. Third, the logger object passes the relevant log messages to all interested log processors.

The commonly used methods of the logger object fall into two categories: configuring and sending messages.

These are the most commonly used configuration methods:

() specifies the lowest security level log message that the logger will process, debug is the lowest built-in security level, and critical is the highest built-in security level. For example, if the severity level is INFO, the logger will only process INFO, WARNING, ERROR, and CRITICAL messages; DEBUG messages are ignored.
() and () add and remove handler objects from the logger object. Handlers are detailed in Handlers.
() and () add and remove filter objects from the logger object.

Handlers

The handler object is responsible for dispatching the appropriate log message (based on the severity of the log message) to the specified target of the handler.The Logger object can add zero or more handler objects via the addHandler() method. For example, an application could send all log messages to a log file, all error level and higher log messages to standard output, and all critical log messages 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 four commonly used:

1) -> Console Outputs

Use this Handler to output information to any file object similar to or.

Its constructor is:

StreamHandler([strm])

where the strm argument is a file object. The default is

2) -> File Output

Similar to StreamHandler for outputting log messages to a file. But FileHandler will open the file for you. Its constructor is:
FileHandler(filename[,mode])

filename is the filename, a filename must be specified.

mode is the way the file is opened. The default is 'a', which means add to the end of the file.

3) -> Automatically splits the log file by size and regenerates the file once it reaches the specified size.

This handler is similar to the FileHandler above, but it can manage the file size. When the file reaches a certain size, it will automatically rename the current log file and create a new log file with the same name to continue output. For example, the log file is. When the specified size is reached, RotatingFileHandler automatically renames the file to .1. However, if .1 already exists, it will first rename .1 to .2. Finally, it recreates , and continues to output log messages. Its constructor is:

RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])

The parameters filename and mode are the same as FileHandler.

maxBytes is used to specify the maximum file size of the log file. If maxBytes is 0, it means that the log file can be infinitely large, and then the renaming process described above will not happen.

backupCount is used to specify the number of backup files to keep. For example, if 2 is specified, when the renaming process described above occurs, the original .2 will not be renamed, but deleted.

4) -> Auto-split log files by time

This handler is similar to the RotatingFileHandler, but instead of determining when to recreate the log file by determining the size of the file, it automatically creates a new log file at regular intervals. The renaming process is similar to RotatingFileHandler, but instead of appending a number, the new file is the current time. Its constructor is:

TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])

The filename and backupCount parameters have the same meaning as RotatingFileHandler.

interval is the time interval.

The when parameter is a string. It indicates the unit of the time interval and is not case sensitive. It has the following values:

S sec.

Subtotal M

H hours

D Day

W Weekly (interval==0 for Monday)

midnight Every morning.

Configuration method:

  • The setLevel() method, like the Log object's, specifies the lowest level at which the log will be distributed. Why are there two setLevel() methods? The level of the logger determines whether the message is to be passed to a processor. The level of each processor determines whether the message is to be distributed.
  • setFormatter() selects a formatter for this processor.
  • addFilter() and removeFilter() configure and de-configure the filter object on the handler, respectively.

Formatters

Formatter object to set the rules, structure and content of the last log message, the default time format is %Y-%m-%d %H:%M:%S, the following is the Formatter commonly used some of the information

%(name)s

Logger's name

%(levelno)s

Log level in numeric form

%(levelname)s

Log level in text form

%(pathname)s

The full pathname of the module that calls the log output function, which may not have a

%(filename)s

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

The name of the function that calls the log output function

%(lineno)d

The 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 number that represents time.

%(relativeCreated)d

The number of milliseconds since the logger was created when outputting log messages.

%(asctime)s

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

%(thread)d

Thread ID. may not have

%(threadName)s

Thread Name. There may be no

%(process)d

Process ID. may not have

%(message)s

User Output Messages

Demand:

Outputs logs to the console and writes logs to a log file.

Saves two types of logs, debug, info, warning, critical, and error, and automatically splits the log file according to time.

import logging
from logging import handlers

class Logger(object):
 level_relations = {
 'debug':,
 'info':,
 'warning':,
 'error':,
 'crit':
 }# Log level relationship mapping

 def __init__(self,filename,level='info',when='D',backCount=3,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
  = (filename)
 format_str = (fmt)# Set the log format
 (self.level_relations.get(level))# Set log level
 sh = ()# Output to the screen
 (format_str) # Set the format displayed on the screen
 th = (filename=filename,when=when,backupCount=backCount,encoding='utf-8')# Write to file # Specify the processor that automatically generates the file at intervals
 #InstantiateTimedRotatingFileHandler
 #interval is the time interval, backupCount is the number of backup files, if it exceeds this number, it will be deleted automatically, when is the time unit of the interval, the units are as follows:
 # S seconds
 # M points
 # H hours,
 # D-day,
 # W per week (intervals==0 for Monday)
 # midnight Every morning
 (format_str)# Set the format of what is written in the file
 (sh) # Add the object to the logger
 (th)
if __name__ == '__main__':
 log = Logger('',level='debug')
 ('debug')
 ('info')
 ('Warning')
 ('Report an error')
 ('Serious')
 Logger('', level='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: debug
2018-03-13 21:06:46,092 - D:/write_to_log.py[line:26] - INFO: info
2018-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: reporting error
2018-03-13 21:06:46,099 - D:/write_to_log.py[line:29] - CRITICAL: serious
2018-03-13 21:06:46,100 - D:/write_to_log.py[line:30] - ERROR: error

Since when=D, the newly generated file name will carry the time with it as follows.

summarize

to this article on Python+logging output to the screen will log logs written to the file of the article is introduced to this, more related Python+logging output to the screen content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!