Let's study Python

Logger Adapter in Python’s logging module enhances Logger Instance messages with additional information using the process method.

# Python Class logging.LoggerAdapter Usage

Logger Adapter is used in Python’s logging module to include additional information when Logger Instance outputs a message in addition to the original format. By creating a LoggerAdapter instance, the process method, a Member Method, can be used to add new information to the message passed. Naturally, when attempting to output the message, the modified message with added information will be displayed.

According to the Logger Adapter documentation (https://docs.python.org/ko/3/howto/logging-cookbook.html#context-info), it states, ‘Two instances can be used with the same meaning.’ This statement might be initially confusing, but it means that you can use two types of instances interchangeably.

If we look at the example code:
“`python
logger = logging.getLogger(‘tester’)
extra = {“log_level”: level} # level is an already in use variable‚Ķ.
logger = logging.LoggerAdapter(logger, extra)
“`

It might seem like the variable “logger” is first created as a Logger Instance, then it appears to be changed to a LoggerAdapter Instance. However, in the constructor of LoggerAdapter, a pre-existing Logger object is passed as an argument. Thanks to this, the LoggerAdapter now has the previously created logger as a Member element. Moreover, all functions provided by the Logger are also included in the LoggerAdapter.

Therefore, except for adding the extra key (a feature unique to LoggerAdapter), the way of using LoggerAdapter is the same as using Logger. When calling functions of LoggerAdapter, they internally call the Logger function with the Logger Instance passed during creation.

In the end, ‘Two instances can be used with the same meaning’ means that the usage of LoggerAdapter Instance and Logger Instance is similar, so there is no need for the user to clearly distinguish between the two instances when using them.

### Creating Derived Functions for LoggerAdapter

While using LoggerAdapter, there might be instances where the default implemented functions do not work as desired. In such cases, you can directly implement a derived class of LoggerAdapter to add the desired functionality or override existing functions.

“`python
class CustomAdapter(logging.LoggerAdapter):
def process(self, msg, kwargs):
return msg, kwargs
“`

The above content overrides the process function of LoggerAdapter. In the original process, the statement `kwargs[“extra”] = self.extra` is written above the return statement. I wanted to replace the extra value with the input value every time a log is output, so by removing that statement, I was able to easily implement the functionality I desired.

This showcases the flexibility and extensibility of the LoggerAdapter class in Python’s logging module.

#Python3 #logging #LoaggerAdapter