redirect prints to log file
Asked Answered
E

10

52

Okay. I have completed my first python program.It has around 1000 lines of code. During development I placed plenty of print statements before running a command using os.system() say something like,

print "running command",cmd
os.system(cmd)

Now I have completed the program. I thought about commenting them but redirecting all these unnecessary print (i can't remove all print statements - since some provide useful info for user) into a log file will be more useful? Any tricks or tips.

Epicurus answered 25/3, 2010 at 6:25 Comment(3)
i think simple code snippet provided by Michel will fulfill my requirements ...thank you allEpicurus
I tried the accepted answer's code but didn't really work. #54049735Mars
related: https://mcmap.net/q/63445/-making-python-loggers-output-all-messages-to-stdout-in-addition-to-log-fileLarcener
S
74

Python lets you capture and assign sys.stdout - as mentioned - to do this:

import sys
old_stdout = sys.stdout

log_file = open("message.log","w")

sys.stdout = log_file

print "this will be written to message.log"

sys.stdout = old_stdout

log_file.close()
Silicify answered 25/3, 2010 at 6:35 Comment(6)
You can also do -- sys.stdout = sys.__stdout__ -- instead of using old_stdout.Stilly
This is a messy hack, but certainly possible. If you do use it, reset sys.stdout to its original value in the finally block of a try/finally.Iorgos
@007brendan, that assumes that sys.stdout starts as sys.__stdout__. That isn't a great assumption, someone else could be redirecting sys.stdout for a purpose like this or for a more sane use, like a system where a whole app's stdout really shouldn't be sys.__stdout__.Iorgos
I tried the code but didn't really work. What's wrong with this? #54049735Mars
works! python3.6 also works, need to be careful to close the opened file at the endSpitter
Michael's answer works on python3.8. Can define a custom print function using this.Mcleroy
H
66

You should take a look at python logging module


EDIT: Sample code:

import logging

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG, filename="logfile", filemode="a+",
                        format="%(asctime)-15s %(levelname)-8s %(message)s")
    logging.info("hello")

Produce a file named "logfile" with content:

2012-10-18 06:40:03,582 INFO     hello
Handfasting answered 25/3, 2010 at 6:27 Comment(5)
+1 for the logging module. Gives you wayyyy more control than print statements.Stilly
Your solution doesn't in fact answer the question of "how to redirect output" at all! Go to that page - search (in vain) for any hint of how to redirect logging to a file. The actual solution is on the page for logging.config - but I defy you to locate it there. onlamp.com/pub/a/python/2005/06/02/logging.html might be a better example.Shamikashamma
@TomSwirly at the bottom of the page: a link to docs.python.org/library/… gives you a page where FileHandler is explainedHandfasting
@TomSwirly and the page also explain basicConfigHandfasting
You're right, it is at the bottom of that page, but by being wrong I improved your answer, so it worked out!Shamikashamma
I
12
  • Next time, you'll be happier if instead of using print statements at all you use the logging module from the start. It provides the control you want and you can have it write to stdout while that's still where you want it.

  • Many people here have suggested redirecting stdout. This is an ugly solution. It mutates a global and—what's worse—it mutates it for this one module's use. I would sooner make a regex that changes all print foo to print >>my_file, foo and set my_file to either stdout or an actual file of my choosing.

    • If you have any other parts of the application that actually depend on writing to stdout (or ever will in the future but you don't know it yet), this breaks them. Even if you don't, it makes reading your module look like it does one thing when it actually does another if you missed one little line up top.
    • Chevron print is pretty ugly, but not nearly as ugly as temporarily changing sys.stdout for the process.
    • Very technically speaking, a regex replacement isn't capable of doing this right (for example, it could make false positives if you are inside of a multiline string literal). However, it's apt to work, just keep an eye on it.
  • os.system is virtually always inferior to using the subprocess module. The latter needn't invoke the shell, doesn't pass signals in a way that usually is unwanted, and can be used in a non-blocking manner.

Iorgos answered 25/3, 2010 at 14:49 Comment(0)
H
6

You can create a log file and prepare it for writing. Then create a function:

def write_log(*args):
    line = ' '.join([str(a) for a in args])
    log_file.write(line+'\n')
    print(line)

and then replace your print() function name with write_log()

Hy answered 1/12, 2017 at 14:8 Comment(0)
H
2

You can redirect replace sys.stdout with any object which has same interface as sys.stdout, in that object's write you can print to terminal and to file too. e.g. see this recipe http://code.activestate.com/recipes/119404-print-hook/

Hyperaemia answered 25/3, 2010 at 6:56 Comment(5)
Though applicable, that recipe is stylistically, semantically, and conceptually awful.Iorgos
@Mike Graham, hey i wrote that 8 years ago :), anyway why is that so awful ?Hyperaemia
I would avoid using something like that if I could possibly do so for a couple reasons. It changes a global value (sys.stdout) for local use and may have accidental, far-off, unexpected effects (this is the reason people avoid using global state). When it's done, it restores the value to sys.__stdout__, which may and may not be what sys.stdout started as depending on if someone else was doing this sort of trick. It does not have a usage such that an unexpected exception won't leave sys.stdout stuck at an unwanted value later.Iorgos
That being said, I'm sorry to have been uncivil. Though I honestly believe the best solution will not use this kind of technique, I was unduly harsh in my criticism.Iorgos
@Mike Graham that is fine, criticism is good, and that hook is hack to divert all the prints of app if need be, in practical situation I have used it on some old apps which have print littered all aroundHyperaemia
G
2

A simple way to redirect stdout and stderr using the logging module is here: How do I duplicate sys.stdout to a log file in python?

Gosplan answered 25/3, 2010 at 7:41 Comment(5)
That solution is disgusting and not even entirely applicable (in that it writes to stdout and a file; OP only wants to write to a file.)Iorgos
Please could you explain why this is "disgusting"? I know redirecting stdout is a bad idea but sometimes it's worth doing: this week I did it to run django on a server overnight for testing, and django's runserver command prints to stdout. Also, please test your opinion before posting because the solution in question does not write to stdout. I have just tested it again.Gosplan
This is disgusting because it uses globals. This means that when you read print foo it doesn't do what you expect it to without reading where the global was changed, which might not even be in the same file as the print statement. It's unmodular because multiple things can't all do this sanely. You even acknowledge that it's a bad idea. When something should be printed to stdout but you want to redirect it, there are tools for this (like > on the shell); when something should be written somewhere other than stdout, you should make your code write there instead.Iorgos
I apologize about my statement about the code writing to a file and stdout. I was looking at a different solution in the same thread as you linked. My mistake.Iorgos
Apology accepted. Thanks for the clarification. I agree one should avoid messing with globals. I have updated my original post to point out that the logging module should be used directly wherever possible. This is what I always intended but didn't say it explicitly until now.Gosplan
S
2

there are many way to write output into the '.log' file

Logging is a means of tracking events it happen when some file runs. Is also indicate that certain events have occurred.

import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This is debug message')
logging.info('This is information message')
logging.warning('This is warning message')
logging.error('This is warning message')

another method to use to reduce all that thing sinple what ever you print to the console that all will be saved to the ''log'' file

python abc.py > abc.log

by using this method you can write everything to the log file

Sinclare answered 25/4, 2021 at 17:59 Comment(0)
U
1

Putting your own file-like in sys.stdout will let you capture the text output via print.

Uncontrollable answered 25/3, 2010 at 6:27 Comment(1)
This is true but awful and shouldn't be used.Iorgos
R
0

Just a note about append vs write mode. Change filemode to "w" if you would like it to replace log file. I also had to comment out the stream. Then using logging.info() was outputting to file specified.

if __name__ == '__main__':
    LOG_FORMAT = '%(asctime)s:%(levelname)s ==> %(message)s'
    logging.basicConfig(
        level=logging.INFO,
        filename="logfile",
        filemode="w",
        format=LOG_FORMAT
        #stream=sys.stdout
    )
Radio answered 1/7, 2019 at 0:41 Comment(0)
V
0
def log(txt):
    f = open(__file__ + '.log', "a")
    f.write(txt + '\r\n')
    f.close()

Usage:

log('Hello World!')

Example:

python3 helloworld.py

Will append to file ./helloworld.py.log. If file doesn't exist, it will create it.

Venavenable answered 21/1, 2022 at 19:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.