如何在python日志记录中插入换行符? [英] How to insert newline in python logging?
问题描述
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S')
logging.info('hello')
logging.warning('\n new hello')
11:15:01信息你好
11:16:49警告
新问好
11:15:01 INFO hello
11:16:49 WARNING
new hello
由于日志很拥挤,我想在之前 asctime
和levelname
显式插入换行符.无需修改format
,这是否可能?
Because the log is crowded, I want to explicitly insert a newline before asctime
and levelname
. Is this possible without modifying format
?
我调查了logging
模块并用谷歌搜索了一下,找不到可行的方法.
I looked into logging
module and googled a bit and could not find a viable way.
推荐答案
我有两个解决方案,第一个很简单,但是输出不是很干净.第二种方法将产生所需的确切输出,但涉及更多.
I have two solutions, the first is very easy, but the output is not very clean. The second method will produce the exact output you want, but it is a little more involved.
要产生空白行,只需用新行记录一个空字符串:
To produce a blank line, just log an empty string with a new line:
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S')
logging.info('hello')
logging.info('\n')
logging.warning('new hello')
输出将有一个空的信息行,这不是很干净:
The output will have an empty info line, which is not very clean:
16:07:26信息你好
16:07:26信息
16:07:26 INFO hello
16:07:26 INFO
16:07:26警告您好
16:07:26 WARNING new hello
方法2
在此方法中,我创建了两个不同的处理程序.我大部分时间使用的console_handler
.当我需要换行时,我切换到第二个处理程序blank_handler
.
Method 2
In this method, I created two different handlers. The console_handler
which I use most of the time. When I need a new line, I switch to a second handler, blank_handler
.
import logging
import types
def log_newline(self, how_many_lines=1):
# Switch handler, output a blank line
self.removeHandler(self.console_handler)
self.addHandler(self.blank_handler)
for i in range(how_many_lines):
self.info('')
# Switch back
self.removeHandler(self.blank_handler)
self.addHandler(self.console_handler)
def create_logger():
# Create a handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(logging.Formatter(fmt="%(name)s %(levelname)-8s: %(message)s"))
# Create a "blank line" handler
blank_handler = logging.StreamHandler()
blank_handler.setLevel(logging.DEBUG)
blank_handler.setFormatter(logging.Formatter(fmt=''))
# Create a logger, with the previously-defined handler
logger = logging.getLogger('logging_test')
logger.setLevel(logging.DEBUG)
logger.addHandler(console_handler)
# Save some data and add a method to logger object
logger.console_handler = console_handler
logger.blank_handler = blank_handler
logger.newline = types.MethodType(log_newline, logger)
return logger
if __name__ == '__main__':
logger = create_logger()
logger.info('Start reading database')
logger.info('Updating records ...')
logger.newline()
logger.info('Finish updating records')
输出就是您想要看到的:
The output is what you want to see:
logging_test INFO : Start reading database
logging_test INFO : Updating records ...
logging_test INFO : Finish updating records
讨论
- 如果您可以接受效果不理想的输出,则方法1是可行的.它的优点是简单,省力.
- 第二种方法可以正确地完成工作,但是涉及到一点点.它会创建两个不同的处理程序并进行切换,以实现您的目标.
- 使用方法2的另一个缺点是,您必须通过搜索
logging
并将其替换为logger
来更改代码.您必须注意只更换相关的部件,并保留诸如logging.DEBUG
之类的文本. - If you can put up with the less-than-perfect output, method 1 is the way to go. It has the advantage of being simple, least amount of effort.
- The second method does the job correctly, but it is a little involved. It creates two different handlers and switch them in order to achieve your goal.
- Another disadvantage of using method 2 is you have to change your code by searching for
logging
and replacing them withlogger
. You must take care replacing only relevant parts and leave such text aslogging.DEBUG
in tact.
Discussion
这篇关于如何在python日志记录中插入换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!