简体   繁体   English

使用线程局部变量进行Python日志记录

[英]Python logging with thread locals

I'd like to prepend the user email to all web app logs. 我想在所有网络应用日志中添加用户电子邮件。

I can store the email (taken from the cookie and such) in threading.local() . 我可以将电子邮件(从cookie等获取)存储在threading.local() But I can't be always sure the variable will be there in the thread locals. 但是我不能总是确定变量是否在线程本地变量中。

Is there a way to tell all the loggers in my app to act like that? 有没有办法告诉我的应用程序中的所有记录器都这样操作?

You can create a logging.Filter() object that grabs the thread-local variable (or a suitable default when its not there) and add it to the log record. 您可以创建一个logging.Filter()对象,该对象将获取线程局部变量(或当线程局部变量不存在时使用合适的默认值)并将其添加到日志记录中。 Attach that filter to the root logger and it will be called for all log records before they are passed to handlers. 将该过滤器附加到根记录器,在将所有日志记录传递到处理程序之前,将对其进行调用。 Once the variable is in the log record it can be used in the formatters you use to display/save the information. 一旦变量在日志记录中,就可以在用于显示/保存信息的格式化程序中使用它。

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

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