1. Overall explanation
1. Problem background
You can use print to print logs in python, but the print is messy and does not take time, which looks very unsightly. You need to customize a tool with different log levels
usage
In Python,print
is a built-in function that outputs representations of text or other objects to standard output (usually console). It is a commonly used way of debugging and outputting information.
print
The basic syntax of a function is as follows:
print(value1, value2, ..., sep=' ', end='\n', file=, flush=False)
in:
-
value1, value2, ...
is the value or object to be printed. Multiple values can be separated by commas. -
sep
is a string used to separate multiple values, and defaults to a space. -
end
It is a string at the end of printing, and the default is a newline character.\n
。 -
file
is the output file object, defaulting to standard output (console). -
flush
is a boolean value indicating whether the output is refreshed immediately. The default isFalse
。
Here are some examples:
print("Hello, world!") # Print a string name = "Alice" age = 25 print("Name:", name, "Age:", age) # Print multiple values, using default delimiters and newlines print("Hello", "world", sep="-") # Use custom delimiters print("Hello", end="") # No line break output file = open("", "w") print("Hello, file!", file=file) # Output to file print("Hello, flush!", flush=True) # Refresh the output immediately
After running the above code, you will see the corresponding output results in the console or in the specified file.
print
Functions are very useful when debugging code, outputting program running results, and providing information to users. You can use it flexibly as you need to meet different printing needs
3. Log level
In software development and logging, commonly used log levels (Log Levels) usually follow the following standard hierarchy:
DEBUG: The lowest level log is used to output detailed debugging information. Usually used only during the development and debugging phases to track details during code execution.
INFO (information): used to output general information during program operation, such as program startup, key events, operation success, etc. It provides a holistic understanding of program behavior.
WARNING: Used to output warning messages that may cause problems or potential errors, which will not cause program interruption or fatal errors, but require attention.
ERROR: Used to output error information, indicating that an error occurred at a specific point, but it does not cause the program to terminate. Error logs usually indicate that an unexpected situation has occurred on the program.
CRITICAL: The highest level log for outputting critical and fatal errors. It means that the program has encountered serious problems that cannot continue execution and may cause the program to crash or fail to run properly.
In addition, there are some other log levels, whose specific names and definitions may vary according to different log libraries and frameworks. For example:
- TRACE: A more detailed log level than DEBUG, used to output more granular information than debug level.
- FATAL (fatal): is equivalent to CRITICAL, used to indicate a fatal error.
Note that different log libraries and frameworks may differ in naming and definition of these log levels. When using it, you can select the appropriate logging level based on your specific needs and the documentation of the logging library.
2. Code implementation
1. Complete code
import logging class TimeStampedLogger: def __init__(self, log_level=): = self._configure_logger(log_level) def _configure_logger(self, log_level): logger = (__name__) (log_level) formatter = ('%(asctime)s - %(message)s') stream_handler = () stream_handler.setFormatter(formatter) (stream_handler) return logger def info(self, message): (message) def debug(self, message): (message) logger = TimeStampedLogger()
2. Extended method
You can add logs of different levels
def info(self, message): (message) def debug(self, message): (message)
Attachment: Print logs, files, line numbers, current time in Python
Write a function to implement the logging function of python:
Call the function, print the current time, print the current line number, file function name
Easy to find bugs
import sys,time def Log(msg,line,name): #File address __file__, optionally add date = ('%Y.%m.%d %H:%M:%S ',(())) print(date+':'+ msg +', Line '+line+' , in '+name) if __name__ == '__main__': Log('hello',str(sys._getframe().f_lineno),sys._getframe().f_code.co_name) #2022.03.25 11:52:15 :hello, Line 9 , in <module>
Print result: 2022.03.25 11:52:15 :hello, Line 9, in <module>
Summarize
This is the end of this article about the implementation of python printing logs with time. For more related python printing logs with time, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!