Selorbis
Selorbis

Reputation: 571

Python Logging - Use a pre-format message file with key/code

I want to use Logging with a dictionary of message.

The logger have for example a formatters attached :

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

I want to have a file like this for example with a pre configuration format message:

ERROR-1234 : "The entity : {1} doesn't exist"
ERROR-4321 : "The client : {1} with the name {2} doesn't exist"

When I make the call maybe like that :

logger.error(ERROR-1234, "entity-1")
logger.error(ERROR-4321, "25", "John Smith")

And the result

2018-05-31 16:55:42,584 - Example - ERROR- The entity : entity-1 doesn't exist}
2018-05-31 16:55:42,584 - Example - ERROR- The client : 25 with the name John Smith doesn't exist}

Can we do this behaviour (like Log4J) with logging librairy ?

Thanks

Upvotes: 1

Views: 37

Answers (1)

wim
wim

Reputation: 362786

Make a module:

# my_error_messages.py
errors = {
    1234: "The entity : %s doesn't exist",
    4321: "The client : %s with the name %s doesn't exist",
}

In your code:

from my_error_messages import errors

logger.error(errors[4321], "25", "John Smith")

Upvotes: 2

Related Questions