[Tutor] Save output to log file

Cameron Simpson cs at cskk.id.au
Mon Aug 17 04:53:24 EDT 2020


On 17Aug2020 08:58, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
>On 17/08/2020 05:36, Phaik Huen Tan wrote:
>> I am supposed to create a network monitoring tool using python and send the
>> output to log file. I have been searching online and don't have any luck
>> finding how to send the result to log file. Can you please give me example
>> on how to send the log from the output?
>
>A log file is just a file. So if you can write to any file
>you can write to a log file. The simplest way to  to that is just
>to use print statements then, when you run the code use
>output redirection to your log file
>
>$ python myprog.py > mylogfile.txt

I'd add two important things here:

First, log files generally grow. So the above line should always look 
like this:

    $ python myprog.py >> mylogfile.txt

to append to the file if it already exists. If you're opening the log 
file from within your python programme this would look like:

    logfile = open(logfile_pathname, 'a')   # open for append

Second, generally it is useful to include a timestamp on everything you 
write to a log file - that way you know when things happened when you 
review the log.

Finally, the logging module, which Alan mentions:

>But assuming you need something more sophisticated than that
>you can use the logging module that comes with Python.
>Check the documentation for many examples.

The logging module docs are here:

    https://docs.python.org/3/library/logging.html#module-logging

The basic deal is that you configure the logging when your programme 
commences, and then broadly just use debug(), info(), warning() and 
error() logging calls elsewhere. The configuration is where you set up 
things like log filenames and the format for the log messages. Then the 
various log calls just contain the message itself, all the things like 
putting it in the right file, with a timestamp etc are already done.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list