AdamDynamic
AdamDynamic

Reputation: 791

Python logging module - output to text file when running from command line

I have a python program that uses the logging module to output data to a text file, the problem I have is that the output to the text file works fine when I run the script in PyCharm (the 1-10 values are output to both the console screen and written to Log_Test_File.txt), but when I run the script from the command line only the console output appears (with nothing written to the *.txt file). This occurs in both Ubuntu or on my Raspberry Pi.

I'll be running the script on the Pi automatically on start-up (as sudo), is there a way to configure either the Pi or the script so that the text output works correctly?

#!/usr/bin/python
# -*- coding: utf-8 -*-

import logging

logging.basicConfig(filename="Log_Test_File.txt",
                level=logging.DEBUG,
                format='%(levelname)s: %(asctime)s %(message)s',
                datefmt='%m/%d/%Y %I:%M:%S')

i=0
while i<10:
    logging.info("Logging test: {}".format(i))
    i+=1

Upvotes: 6

Views: 12585

Answers (1)

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44102

The code you have provided runs well.

If you have problems with finding the log file being properly created, the reasons might be:

  • not having permission to create the log file
  • the script does not run at all

If you plan to run the script as long running service, I would recommend to skip creating explicit log file and rather log to stdout. The output sent to stdout is easy to see, capture and process by program controlling execution of the script (e.g. supervisord, systemd etc.).

Another option would be to log to syslog directly, but this could become more complicated as your program would have to know on it's own, what values to use for identifying the process. This is mostly simpler for process manager then for the program itself.

Upvotes: 3

Related Questions