简体   繁体   English

在日志文件中每一行的开头打印特定的字符串

[英]Print specific string at the beginning of each line in log file

How can I setup python's module logging so that every line it prints to the file starts with a specific string?如何设置 python 的模块logging ,以便它打印到文件的每一行都以特定字符串开头?

You can do this via the log formatter .您可以通过日志格式化程序执行此操作。 Here's a simple example configuring it via logging.basicConfig :这是一个通过logging.basicConfig配置它的简单示例:

import logging
logging.basicConfig(format="Hello at %(asctime)s %(message)s: %(levelname)s")
logging.warning("world")

Using python logging使用 python 记录

Formatting the Output格式化 Output

You can pass any variable that can be represented as a string from your program as a message to your logs.您可以将任何可以表示为字符串的变量从您的程序作为消息传递到您的日志。 If you for example want to log the process ID along with the level and message, you can do something like this:例如,如果您想记录进程 ID 以及级别和消息,您可以执行以下操作:

import logging

logging.basicConfig(format='%(process)d-%(levelname)s-%(message)s')
logging.warning('This is a Warning')

# Output:
# 18472-WARNING-This is a Warning

For further details see documentation on realpython.有关更多详细信息,请参阅 realpython 上的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM