john
john

Reputation: 4158

Python logging won't write to file

So I'm using an exception logging module I found and tweaked slightly. But I can't seem to figure out why it won't create a file and write to it.

This is my module:

"""Exception logging"""
import sys
import traceback
import logging

logger = logging
def setup_logging_to_file():
    logger = logging.basicConfig( filename='error_log.txt',
                                filemode='w',
                                level=logging.DEBUG,
                                format= '%(asctime)s - %(levelname)s - %(message)s',
                            )


def log_exception(e):
    logger.error(
    "Function {function_name} raised {exception_class} ({exception_docstring}): {exception_message}".format(
    function_name = extract_function_name(), #this is optional
    exception_class = e.__class__,
    exception_docstring = e.__doc__,
    exception_message = e.message))

def extract_function_name():
    tb = sys.exc_info()[-1]
    stk = traceback.extract_tb(tb, 1)
    fname = stk[0][3]
    return fname

I run setup_logging_to_file() on start up then whenever I hit an exception I call log_exception and pass it the exception but it won't even create the error_log.txt file

from app.exception_logging import log_exception, setup_logging_to_file

def myFunc():
    try:
        ....
    except Exception as ex:        
        log_exception(ex)

Upvotes: 1

Views: 2889

Answers (2)

Amirkhm
Amirkhm

Reputation: 1096

I had the same problem. At the end I resolved to do as following:

import logging.config

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("log_file.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

And then in the code, you may use the logger as following:

logger.info('message')
logger.error('message')

Upvotes: 1

joeButler
joeButler

Reputation: 1711

As suggested in the comments - you can access logging directly.

Working example, file called logtest.py:

"""Exception logging"""
import sys
import traceback
import logging

logging.basicConfig( filename='/tmp/error_log.txt',
                            filemode='w',
                            level=logging.DEBUG,
                            format= '%(asctime)s - %(levelname)s - %(message)s',
                )


def log_exception(e):
    logging.error(
    "Function {function_name} raised {exception_class} ({exception_docstring}): {exception_message}".format(
    function_name = extract_function_name(), #this is optional
    exception_class = e.__class__,
    exception_docstring = e.__doc__,
    exception_message = e.message))

def extract_function_name():
    tb = sys.exc_info()[-1]
    stk = traceback.extract_tb(tb, 1)
    fname = stk[0][3]
    return fname

destination file:

from logtest import log_exception

try:
   open("somthingnotthere",'r')
except Exception as ex:        
    log_exception(ex)

Upvotes: 0

Related Questions