0

I have a Rabbitmq consumer that gets messages from another service with a unique_id. I need to set some environment variables which prints in every log within that process message block.

import logging
import os

LOG_FORMAT = '%(asctime)s - %(levelname)-7s %(message)s  : unique_id  : os.getenv("unique_id","1")'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)

also updating os var before message process block:

os.environ["unique_id"] = new_unique_id

however, with the above code log format is not taking the latest value of unique_id. It always prints 1. Seems it only takes value while initialization.

I only want to append unique_id for each log message in that particular block with updated unique_id. As it is a very big project so I don't want to append this to each log manually. I want to use a log format here.

New to the python, so not able to understand what I am doing wrong.

3
  • Yes, the LOG_FORMAT will be fixed to the time when logger is configured. If you just want to prefix the logs, why not add it to your log message instead? logging.info(os.getenv("unique_id", "1") + "your message here") or create a function to wrap around logging calls? or check this answer Commented Jun 9, 2020 at 7:32
  • you can define your own values that you can use in the logging format. you could also use a logging adapter or filter for your particular logger, which sets the corresponding extra value. see: stackoverflow.com/questions/17558552/… you could also use a mapped diagnostic context in your code, in java this is common practice, in python you'd have e.g. pypi.org/project/mdc. Commented Jun 9, 2020 at 7:59
  • ...the MDC will allow you to temporarily set contextual values (your unique id) that you can use in your log messages within a given code block. Commented Jun 9, 2020 at 8:10

0

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.