Solved

output to a text file a

Posted on 2011-09-13
8
521 Views
Last Modified: 2012-05-12
I want to the logger to output to a text file and not to the screen... How can I do that

import logging, mymodule

logging.basicConfig()

log = logging.getLogger("MyApp")
log.setLevel(logging.DEBUG) #set verbosity to show all messages of severity >= DEBUG
log.info("Starting my app")
try:
    mymodule.doIt()
except Exception, e:
    log.exception("There was a problem.")
log.info("Ending my app")

Open in new window

0
Comment
Question by:dolamitejenkins
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 29

Expert Comment

by:pepr
ID: 36534274
You have to tell the filename to the logging.basicConfig().  See http://docs.python.org/howto/logging.html#logging-to-a-file

Try:
import logging

logging.basicConfig(filename='mylog.txt')

log = logging.getLogger("MyApp")
log.setLevel(logging.DEBUG) #set verbosity to show all messages of severity >= DEBUG
log.info("Starting my app")
try:
    i = 5 / 0
except Exception as e:
    log.exception("There was a problem." )
log.info("Ending my app")

Open in new window


0
 

Author Comment

by:dolamitejenkins
ID: 36536163
thanks
0
 

Author Comment

by:dolamitejenkins
ID: 36536522
Pepr When I set up my logger how do I have it record the DEBUG info for every module ?
0
Major Incident Management Communications

Major incidents and IT service outages cost companies millions. Often the solution to minimizing damage is automated communication. Find out more in our Major Incident Management Communications infographic.

 
LVL 29

Expert Comment

by:pepr
ID: 36538197
Frankly, I do not use the logging module, nor I did study deeply the documentation (see http://docs.python.org/howto/logging.html#logging-howto).  Because of that I can only guess what is the usual approach.  But the following worked for me...

Firstly, you can set the name of the log file in the main application only.  Notice that the import of the other modules (here moduleA) is done after that.

myApp.py
import logging
logging.basicConfig(filename='myApplog.txt')

import moduleA

def main():
    log = logging.getLogger(__name__)
    log.setLevel(logging.DEBUG) #set verbosity to show all messages in the main application
    log.info("Starting the application.")

    # Calling the module function (causes logging).
    moduleA.fn()    

    log.info("Finishing the application.")

    
if __name__ == '__main__':
    # Start the body of the application.
    main()

Open in new window


The modules also import the logging module, but they do not set the log filename:


moduleA.py
import logging

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG) #set verbosity to show all messages of severity >= DEBUG
log.info("Starting moduleA")

def fn():
    log.info("fn() called")

Open in new window


The complication is caused only by the approach when the logger (logging.getLogger()) is calling when the module is imported.  Probably more usual approach is the get the logger inside the function that wants to log via the name of the module (I will try and post later).
0
 
LVL 29

Accepted Solution

by:
pepr earned 500 total points
ID: 36538237
Probably more realistic usage just gets the logger just before it is uses and throws it away when not needed.  You can get the same logger again based on its name.  When you always use the __name__ as the logger name, you can be sure that you will use the same logger object (i.e. severity...) inside the module.

myApp.py
import logging
import moduleA

def someFunctionInMain():
    # Get the logger just before you need it.
    log = logging.getLogger(__name__)

    # Use the logger in the app.
    log.info("someFunctionInMain() called.")



def main():
    # Setting the log filename for whole application.
    logging.basicConfig(filename='myApplog.txt')

    # Get the logger just before you need it.
    log = logging.getLogger(__name__)
    log.setLevel(logging.DEBUG) #set verbosity to show all messages in the main application
    
    # Use the logger in the app.
    log.info("Starting the application.")

    # Calling my function withou passing the logger.
    someFunctionInMain()    

    # Calling the module function (also causes logging).
    moduleA.fn()    

    # Use the logger in the app -- we still have the logger,
    # so no need to get it.
    log.info("Finishing the application.")

    
if __name__ == '__main__':
    # Start the body of the application.
    main()

Open in new window


Notice that the import commands appeared just without any commands in between.  The module will use its own logger object (possibly different severity...).

moduleA.py
import logging


def fn():
    # Getting the logger just before we need it.
    log = logging.getLogger(__name__)
    
    # ... possibly setting its verbosity.
    log.setLevel(logging.DEBUG)
    
    # Use the logger.
    log.info("fn() called")

Open in new window



After launching myApp.py, the log file contains:

INFO:__main__:Starting the application.
INFO:__main__:someFunctionInMain() called.
INFO:moduleA:fn() called
INFO:__main__:Finishing the application.

Open in new window

0
 

Author Comment

by:dolamitejenkins
ID: 36539435
thank you pepr ...
0
 

Author Closing Comment

by:dolamitejenkins
ID: 36540517
Pepr you are the best
0
 
LVL 29

Expert Comment

by:pepr
ID: 36541027
You are welcome.  And stop kidding :))  You are also the best.  You only do not know it, yet. ;)  (Part of the reason is that you still have too much hair :)
0

Featured Post

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
OS Selection Menu 1 84
phython 2 64
troubleshoot a python script 8 114
Writing reports to a script 7 29
Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question