Python does not create log file

落花浮王杯 提交于 2020-12-29 09:04:48

问题


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.


回答1:


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



回答2:


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.




回答3:


I found out that my issue was that I was trying to create a log file within nested a nested folder. Once I dumped that idea it became stable.



来源:https://stackoverflow.com/questions/26237870/python-does-not-create-log-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!