将完整日志写入 python 中的文件,而不仅仅是消息
Write full log to file in python not just the message
给定一个像这样的简单代码:
import logging
logging.root.handlers.append(logging.FileHandler("./log.log"))
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - '
'%(filename)s: %(funcName)s(): %(lineno)s: '
'%(message)s', datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
log = logging.getLogger(__name__)
def test():
log.info("Test")
test()
为了将日志同时输出到 stderr 和 log.log 文件,stderr 得到 03/12/2020 14:51:09 - INFO - __main__ - temp.py: test(): 15: Test
而文件只得到 Test
。有没有办法在文件和 stderr 中获取完整的日志行?谢谢
找到了!好的,这比我想象的要容易。我在看错误的东西。这是我的代码,工作起来很有魅力!注意handlers
参数。
import logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - '
'%(filename)s: %(funcName)s(): %(lineno)s: '
'%(message)s', datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO,
handlers=[logging.FileHandler("./log.log"),
logging.StreamHandler()])
log = logging.getLogger(__name__)
def test():
log.info("Test")
test()
当我 运行 这段代码时,我在日志文件和输出流中都得到了下面的行。
03/13/2020 11:35:44 - INFO - __main__ - temp.py: test(): 26: Test
不错!
给定一个像这样的简单代码:
import logging
logging.root.handlers.append(logging.FileHandler("./log.log"))
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - '
'%(filename)s: %(funcName)s(): %(lineno)s: '
'%(message)s', datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
log = logging.getLogger(__name__)
def test():
log.info("Test")
test()
为了将日志同时输出到 stderr 和 log.log 文件,stderr 得到 03/12/2020 14:51:09 - INFO - __main__ - temp.py: test(): 15: Test
而文件只得到 Test
。有没有办法在文件和 stderr 中获取完整的日志行?谢谢
找到了!好的,这比我想象的要容易。我在看错误的东西。这是我的代码,工作起来很有魅力!注意handlers
参数。
import logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - '
'%(filename)s: %(funcName)s(): %(lineno)s: '
'%(message)s', datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO,
handlers=[logging.FileHandler("./log.log"),
logging.StreamHandler()])
log = logging.getLogger(__name__)
def test():
log.info("Test")
test()
当我 运行 这段代码时,我在日志文件和输出流中都得到了下面的行。
03/13/2020 11:35:44 - INFO - __main__ - temp.py: test(): 26: Test
不错!