1
1
10112017-02-28 13:04:42
Python
1011, 2017-02-28 13:04:42

Python logging, how to quickly output errors to a file?

Is it possible to somehow quickly output to a file everything that python outputs to the console? Messages from the print command and errors?
os windows
python 3.4
the program is built by pyinstaller and runs on a third party computer.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
longclaps, 2017-02-28
@1011

I ran something like this in one situation:

old_print = print

def print(*args, **kwargs):
    old_print("~", *args, "~", **kwargs)

print("qwerty")

Keep in mind that print'a substitution operates in the context of the module.
Here is a hint on how to display errors:
from traceback import format_exc

try:
    # do something wrong
    x = 1 / 0
except:
    for s in format_exc().splitlines():
        print("*", s, "*")

Here comrades warmly recommend logging - also an option. It's just not clear from the question what is best for you.

Q
qlkvg, 2017-02-28
@qlkvg

turn on logging before it's too late. Create a logger once and change all print to logger.info - it takes about 5 minutes. In return, you will get the ability to quickly switch logging to a file / console, split messages by levels (it is very convenient to separate debugging messages from informational and diagnostic ones), full-fledged exception logging, and a bunch of other goodies.

S
Sergey Pankov, 2017-05-10
@trapwalker

The very first thing to do in any more or less useful script or large program is to set up logging.
In its simplest form, it can be arranged like this:

import sys
import logging
if __name__ == '__main__':
    log = logging.getLogger()
    log.level = logging.DEBUG
    log.addHandler(logging.StreamHandler(sys.stderr))
else:
    log = logging.getLogger(__name__)

## Используем так:
log.info('any text')
log.debug('Something about %r in %s', log, __name__)

## Здесь размещаем весь остальной код
if __name__ == '__main__':
    pass  # А здесь, если надо, размещаем то, что будет выполняться, когда модуль запускают как скрипт

Here all logging is wrapped in sys.stderr, formatting, output to a file and rotation are not configured. This is the minimum level that makes it possible to refuse print for logging.
Example for python 2.7.
I will add that when this code is run directly, the logger is created with the default name (root). This means that in other modules of the project, control of which is transferred,
log = logging.getLogger(__name__)

will create a logger with the name of the module, and in the main file it will be possible to configure the routing of logs taking into account these names.
Routing is configured by adding additional handlers and various filters to them. If there are any difficulties with this - write, I will explain.
Using the right managed, extensible and flexible logging instead of a scattering of prints is very simple. You just need to accustom yourself to this, as to something mandatory like brushing your teeth, using a version control system and timely backup.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question