![]() |
精明的大白菜 · JS获取点击事件的内容_js点击事件获取当前元素· 1 月前 · |
![]() |
气宇轩昂的大海 · 『现学现忘』Git基础 — 25、git ...· 1 月前 · |
![]() |
个性的单杠 · git - git log ...· 1 月前 · |
![]() |
光明磊落的路灯 · 对于 Git ...· 1 月前 · |
![]() |
爱跑步的松鼠 · Unresolved reference: ...· 1 年前 · |
![]() |
无邪的消炎药 · Excel复选框的基本使用方法,使用VAB代 ...· 1 年前 · |
![]() |
玩手机的吐司 · c++ windows socket ...· 1 年前 · |
我当前的格式字符串是:
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')
但都不管用。
您需要将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
使用mr2ert的答案,我想出了这个舒适的解决方案(尽管我猜不推荐)-覆盖内置的日志记录方法以接受自定义参数,并在方法中创建
extra
字典:
import logging
class CustomLogger(logging.Logger):
def debug(self, msg, foo, *args, **kwargs):
extra = {'foo': foo}
if self.isEnabledFor(logging.DEBUG):
self._log(logging.DEBUG, msg, args, extra=extra, **kwargs)
*repeat for info, warning, etc*
logger = CustomLogger('CustomLogger', logging.DEBUG)
formatter = logging.Formatter('%(asctime)s [%(foo)s] %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.debug('test', 'bar')
输出:
2019-03-02 20:06:51,998 [bar] test
这是供参考的内置函数:
def debug(self, msg, *args, **kwargs):
Log 'msg % args' with severity 'DEBUG'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
if self.isEnabledFor(DEBUG):
self._log(DEBUG, msg, args, **kwargs)
导入日志;
LogFilter类(logging.Filter):
def __init__(self, code):
self.code = code
def filter(self, record):
record.app_code = self.code
return True
消息%( -> )s- APP_CODE:%(app_code)s -MSG:%( logging.basicConfig(format='%(asctime)s:%(levelname)s::%(module)s )s‘);
类记录器:
def __init__(self, className):
self.logger = logging.getLogger(className)
self.logger.setLevel(logging.ERROR)
@staticmethod
def getLogger(className):
return Logger(className)
def logMessage(self, level, code, msg):
self.logger.addFilter(LogFilter(code))
if level == 'WARN':
self.logger.warning(msg)
elif level == 'ERROR':
self.logger.error(msg)
else:
self.logger.info(msg)
类测试: logger = Logger.getLogger('Test')
if __name__=='__main__':
logger.logMessage('ERROR','123','This is an error')
在我自己实现之后,我发现了这个问题。希望这能帮助到别人。在下面的代码中,我在记录器格式中引入了一个名为
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__)