How to optionally pass an parameter to django logging?

Question:

In my django logging settings under formatter – I have a var:

%(new_line_number)s

I have a logging function in my views that calls logger.debug at the end, and so in this case I want to pass newlinenumber.

logger.debug('context for %s: %s', product, tool, extra={'newlinenumber':newlinenumber} )

I do NOT want to have to pass in extra={‘newlinenumber’:None} everytime I call the logger. As that looks very messy and is redundant. How can I accomplish this? Currently if I do not include

extra={'newlinenumber':None}

The logger errors out anytime it has been called without newlinenumber.
The only time I am trying to pass in a newlinenumber is when I call it from my logging function.

Asked By: david

||

Answers:

Maybe something like this?

def my_debug_function(my_str, product, tool, ext={'newlinenumber':None}):
    logger.debug(my_str, product, tool, extra=ext)

And then your usage would be my_debug_function('content for %s, %s', product, tool)

Here, I think I found something better…

def test_log(self, *args, **kwargs):
    kwarg_defaults = {"extra": {"newlinenumber":None}}
    kwarg_defaults.update(kwargs)
    self.debug(*args, **kwarg_defaults)

the usage for this would be the same as whatever your debug is, but it’s not limited to the 3 parameters that the other one was: test_log('content for %s, %s', product, tool)

It’s risky modifying the original logger.debug, but if you’re just pointing to it anyway, there shouldn’t be too much of a problem…

you might say something along the following…

logger.old_debug = logger.debug
def test_log(*args, **kwargs):
    kwarg_defaults = {"extra": {"newlinenumber":None}}
    kwarg_defaults.update(kwargs)
    self.old_debug(*args, **kwarg_defaults)
logger.debug = test_log
Answered By: David Culbreth

Can anyone guide me in this?

  1. Add minimal parameters to logs including user ip address, user ID and time

my-email:[email protected]

Answered By: Sadra Ganjali
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.