Skip to content

Instantly share code, notes, and snippets.

@justinabrahms
Last active December 16, 2015 16:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinabrahms/5465490 to your computer and use it in GitHub Desktop.
Save justinabrahms/5465490 to your computer and use it in GitHub Desktop.
A method of getting per-user logs in python logging. It turns out my original plan which is /var/log/myapp/user.<pk>.log isn't a very good idea from performance b/c you're basically sitting there with a bunch of open files and a bunch of logging handlers each with their own per-user id filter applied. After you get logs in this format, you can w…
class UserLog(object):
"""
Simple log that will output specially formatted user id for logging
purposes.
-1 is used as a sentinal value to mean "no user". Otherwise, the user's `pk`
attribute is logged instead.
An explicit decision was made not to use a LoggerAdapter with a custom
format string because if we attach it to something that isn't the logger
adapter, it explodes.
For more info, see:
http://docs.python.org/2/howto/logging.html#using-arbitrary-objects-as-messages
"""
def __init__(self, msg, user=None):
self.msg = msg
self.user = user
def __repr__(self):
return self.__str__()
def __str__(self):
return "-- user_pk:%s -- %s" % (
self.user.pk if self.user is not None else -1,
self.msg
)
# Example Usage:
from thing_above import UserLog as _
from collections import namedtuple
import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('path.to.module')
user_t = namedtuple('user', 'pk')
log.debug("test") # DEBUG:path.to.module:test
log.debug(_("test with _")) # DEBUG:path.to.module:-- user_pk:-1 -- test with _
log.debug(_("test with _", user=user_t(pk=99))) # DEBUG:path.to.module:-- user_pk:99 -- test with _
@jezdez
Copy link

jezdez commented Apr 26, 2013

I don't understand why you can't use the extra parameter in that case:

FORMAT = '%(levelname)s:%(name)s -- user_pk:%(user)s -- %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)

log = logging.getLogger('path.to.module')
log.debug('test', extra={'user': 1})  # DEBUG:path.to.module -- user_pk:1 -- test

http://docs.python.org/2/library/logging.html#logging.Logger.debug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment