Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python does not create log file

Tags:

python

logging

I am trying to implement some logging for recording messages. I am getting some weird behavior so I tried to find a minimal example, which I found here. When I just copy the easy example described there into my interpreter the file is not created as you can see here:

In [1]: import logging
   ...: logging.basicConfig(filename='example.log',level=logging.DEBUG)
   ...: logging.debug('This message should go to the log file')
   ...: logging.info('So should this')
   ...: logging.warning('And this, too')
WARNING:root:And this, too

In [2]: ls example.log

File not found

Can anybody help me to understand what I am doing wrong? Thanks...

EDIT: changed the output after the second input to English and removed the unnecessary parts. The only important thing is that Python does not create the file example.log.

like image 310
Chris Avatar asked Oct 07 '14 14:10

Chris


2 Answers

The reason for your unexpected result is that you are using something on top of Python (looks like IPython) which configures the root logger itself. As per the documentation for basicConfig(),

This function does nothing if the root logger already has handlers configured for it.

What you get with just Python is something like this:

C:\temp>python
ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec  5 2008, 13:58:38) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> logging.basicConfig(filename='example.log', level=logging.DEBUG)
>>> logging.debug('This message should go to the log file')
>>> logging.info('And so should this')
>>> logging.warning('And this, too')
>>> ^Z

C:\temp>type example.log
DEBUG:root:This message should go to the log file
INFO:root:And so should this
WARNING:root:And this, too
like image 150
Vinay Sajip Avatar answered Sep 21 '22 06:09

Vinay Sajip


Please state which operating system you are using.

Are you running Windows, perhaps using Cygwin? Even if not this looks very much like an environment variable problem. Ensure PYTHONPATH is set correctly. I suggest making a system variable named PYTHONPATH that contains your python install directory (probably something like C:/Python27), and the sub-directories 'Lib', 'Lib/lib-tk' and 'DLLs' directory within this folder as well. See here.

And less likely... Are you running this on a Linux system? Ensure you the appropriate permissions are set on the directory. In bash use 'ls -la' to show the permissions. From the directory run 'chmod u+w .' to ensure you have write permission.

like image 23
DanRea Avatar answered Sep 22 '22 06:09

DanRea