Solved

output to a text file a

Posted on 2011-09-13
8
510 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
  • 4
  • 4
8 Comments
 
LVL 28

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
 
LVL 28

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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 28

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 28

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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

743 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now