Zulan Zulan - 2 months ago 7
Python Question

Create logger that prefixes log messages

Let's say I have a client and server class:

import logging

class Client:
def __init__(self, name):
self.logger = logging.getLogger(self.__class__.__name__)
self.name = name

def foo(self):
self.logger.warn('[%s] foo', self.name)

class Server:
def __init__(self):
self.logger = logging.getLogger(self.__class__.__name__)

def bar(self):

How could I make a logger for the client that will take care of the
prefix magically? The only Idea I have would be to set a global format including
-prefix and using a custom filter for the
. This seems unecessary complicated and global. I feel like there must be a simple way that I just don't see.


This can be done using the logaugment library (disclaimer: I made that library to make it easier but this can also be done using the standard library).

Filling in the client's name can be done as part of a logger's Formatter which formats the log record into a string and at that step you can prefix the message.

Create a logger:

import logging

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter("%(client)s: %(message)s")

Specify the client's name for this logger (i.e., the value to fill in for %(client)s in the above formatted log string:

logaugment.set(logger, client='Client')

From now on you can call logger methods as normal and the client's name will be filled in automatically:

logger.warn("My message")