我当前的格式字符串是:
formatter = logging.Formatter('%(asctime)s : %(message)s')
我想添加一个名为app_name
的新字段,该字段在包含此格式化程序的每个脚本中具有不同的值。
import logging
formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')
syslog.setFormatter(formatter)
logger.addHandler(syslog)
但是我不确定如何将该app_name
值传递给记录器以插入到格式字符串中。很明显,我可以通过每次传递它来让它出现在日志消息中,但这很混乱。
我试过了:
logging.info('Log message', app_name='myapp')
logging.info('Log message', {'app_name', 'myapp'})
logging.info('Log message', 'myapp')
但都不管用。
发布于 2013-07-10 05:40:06
您需要将dict作为参数传递给extra才能做到这一点。
logging.info('Log message', extra={'app_name': 'myapp'})
证明:
>>> import logging
>>> logging.basicConfig(format="%(foo)s - %(message)s")
>>> logging.warning('test', extra={'foo': 'bar'})
bar - test
另外,需要注意的是,如果您试图在不传递dict的情况下记录一条消息,那么它将失败。
>>> logging.warning('test')
Traceback (most recent call last):
File "/usr/lib/python2.7/logging/__init__.py", line 846, in emit
msg = self.format(record)
File "/usr/lib/python2.7/logging/__init__.py", line 723, in format
return fmt.format(record)
File "/usr/lib/python2.7/logging/__init__.py", line 467, in format
s = self._fmt % record.__dict__
KeyError: 'foo'
Logged from file <stdin>, line 1
发布于 2020-04-14 06:36:20
在我自己实现之后,我发现了这个问题。希望这能帮助到别人。在下面的代码中,我在记录器格式中引入了一个名为claim_id
的额外键。每当环境中存在claim_id
密钥时,它都会记录claim_id。在我的用例中,我需要为AWS Lambda函数记录此信息。
import logging
import os
LOG_FORMAT = '%(asctime)s %(name)s %(levelname)s %(funcName)s %(lineno)s ClaimID: %(claim_id)s: %(message)s'
class AppLogger(logging.Logger):
# Override all levels similarly - only info overriden here
def info(self, msg, *args, **kwargs):
return super(AppLogger, self).info(msg, extra={"claim_id": os.getenv("claim_id", "")})
def get_logger(name):
""" This function sets log level and log format and then returns the instance of logger"""
logging.setLoggerClass(AppLogger)
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
return logger
LOGGER = get_logger(__name__)
LOGGER.info("Hey")
os.environ["claim_id"] = "12334"
LOGGER.info("Hey")
要点:https://gist.github.com/ramanujam/306f2e4e1506f302504fb67abef50652
发布于 2020-12-24 14:44:41
接受的答案没有将格式记录在日志文件中,而格式反映在sys输出中。或者,我使用了一种更简单的方法,工作方式为;
logging.basicConfig(filename="mylogfile.test",
filemode="w+",
format='%(asctime)s: ' +app_name+': %(message)s ',
level=logging.DEBUG)
https://stackoverflow.com/questions/17558552
复制相似问题