'A logger embedded in a class loses settings when reading from a pickle

I store my objects with an attribute being a logger in pickle and read them for other programs. I find that the logger's level is lost in the following situation.

In the following example, Cls has an attribute logger with has level logging.INFO (the variable has value of 20)

import pickle
import logging
from pathlib import Path


class Cls(object):
    def __init__(self):
        logger = logging.getLogger('test')
        c_handler = logging.StreamHandler()  # Create handlers
        c_format = logging.Formatter(
            '%(name)s - %(levelname)s - %(message)s')  # Create formatters and add it to handlers
        c_handler.setFormatter(c_format)
        logger.addHandler(c_handler)  # Add handlers to the logger
        logger.setLevel(logging.INFO)
        self.logger = logger

cls = Cls()
cls.logger.info('from logger')  # test


path = Path(__file__).parents[0].joinpath('logger.pickle')
pickle.dump(cls, open(path, 'wb'))  # save to pickle

When reading the pickle file saved from a new python console, using the following script, the attribute level of the logger is reset (see the picture below).

import pickle
import logging
from pathlib import Path


class Cls(object):
    def __init__(self):
        logger = logging.getLogger('test')
        c_handler = logging.StreamHandler()  # Create handlers
        c_format = logging.Formatter(
            '%(name)s - %(levelname)s - %(message)s')  # Create formatters and add it to handlers
        c_handler.setFormatter(c_format)
        logger.addHandler(c_handler)  # Add handlers to the logger
        logger.setLevel(logging.INFO)
        self.logger = logger


path = Path(__file__).parents[0].joinpath('logger.pickle')
cls_new = pickle.load(open(path, 'rb'))
cls_new.logger.info('test')

enter image description here

I could adopt the solution from this post, but I want to avoid invoking getLogger at each time using self.logger.info.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source