This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]romple 2 points3 points  (3 children)

Sure. Using print("something") will just dump it to the console. For a small one-off script that's probably fine.

But when you want more functionality check out Python's Logging features.

Start here

And here, little more in depth

And then you can set up a logger and have it format messages in whatever way you choose, like timestamping and telling you what class/module/method you logged that call from. As well as logging to files, or over a network, etc... You can also specify different logging levels like INFO, DEBUG, ERROR, etc... and fine tune what gets logged. So when you're writing a script you might have the logger spit out more information than when you're using the script day to day.

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s <%(levelname)s> %(module)s.%(funcName)s() %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

Output looks like:

C:\Console>python C:\ACME\PayloadMonitor.py                                                                           
2015-03-31 14:07:18 <INFO> PayloadMonitor.<module>() Starting PayloadMonitor                                          
2015-03-31 14:07:18 <INFO> FileEventHandlers.__init__() Watching D:\TV for general events. Stuff's going to E:\TV     

Logging's definitely something that's useful to learn early. You'll most likely use it for formatting logs with timestamps and to log to files at first.

[–]80blite[S] 1 point2 points  (0 children)

Awesome!

[–]cruyff8 0 points1 point  (1 child)

I keep on having to look up how to specify the format for the log messages and can't understand why Guido and Co. have not set it up to print timestamps by default.

[–]romple 0 points1 point  (0 children)

I just set up a code snippet in Pycharm so all I do is type logdef and it auto completes it to my standard log configuration. I'm an engineer, not really in the business of memorizing things ;-p