0

I want to write all of python logger messages to a log file. I have this code, but the code displays messages on the console and just creates the log file, but writes nothing to it.

file_handler = logging.FileHandler(filename='tmp.log')
stdout_handler = logging.StreamHandler(sys.stdout)
handlers = [file_handler, stdout_handler]

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',
    handlers=handlers
)
logger = logging.getLogger("somename")

What am i doing wrong here

4
  • You mean you want to log all sys.stdout to a file rather than to console? Commented Mar 2, 2019 at 10:52
  • I tried your code example, it logs messages both to sys.stdout and to tmp.log Commented Mar 2, 2019 at 10:54
  • @Lakshita Ranasingha yes i want to print just to the log Commented Mar 3, 2019 at 14:06
  • @Sanya..in my case it just creates the file tmp.log Commented Mar 3, 2019 at 14:07

1 Answer 1

1

do, this instead:

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',
    filename='tmp.log'
)
logging.debug("somename")

If filename parameter is provided in basicConfig it means the file is opened in this mode. The default is a, which means append.

Sign up to request clarification or add additional context in comments.

Comments

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.