1

What I am trying to do is something like this:

def custom_logger(user_logger, log_level, *args, **kwargs):    
    # do some stuff..
    user_logger.log_level(*args, **kwargs)

or like this:

def create_logger(module_name, log_level=DEBUG):
    logger = logging.getLogger(module_name)
    logger.setLevel(logging.log_level)

How can I achieve something like this? Because it will clean up a lot of things.

9
  • 1
    You are mostly correct, but kwargs should have 2 asterisks: **kwargs. Commented Nov 21, 2019 at 19:07
  • Is your question how to pass the function name in the caller, or how to use the function name in the callee? Commented Nov 21, 2019 at 19:09
  • @jknotek, are you telling me that this code will work? Commented Nov 21, 2019 at 19:10
  • 1
    @EzizDurdyyev Well, conceptually, yes, it will work. But I don't know anything about how your logger is implemented. So you'll have to try it yourself and debug as needed. Commented Nov 21, 2019 at 19:12
  • 2
    As written, I don't believe this code will work, because it will call literally user_logger.log_level() instead of using whatever function name was passed as the log_level argument. Commented Nov 21, 2019 at 19:15

1 Answer 1

1

You can use the getattr function to obtain an attribute by name:

def custom_logger(user_logger, log_level, *args, **kwargs):    
    log = getattr(user_logger, log_level) # or log_level.lower() if log_level is in upper case
    # do some stuff..
    log(*args, **kwargs)

def create_logger(module_name, log_level=DEBUG):
    logger = logging.getLogger(module_name)
    logger.setLevel(getattr(logging, log_level))
Sign up to request clarification or add additional context in comments.

2 Comments

how can I apply this to create_logger?
@blhsubg, did you try it before you answered, or you sure this will work with loggers? again, may be i am doing it wrong but.. it won't work with me. sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.