0

I want to replace print statements to logger but without change print statement in application. And how can I redirect print statement to log file???

Below is my code.

settings.py

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "simple": {
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        },
        "verbose": {
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s"
        }
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": "DEBUG",
            "formatter": "simple",
            "stream": "ext://sys.stdout"
        },
        "debug": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "level": "DEBUG",
            "formatter": "verbose",
            "when": "D", # when='D', interval=7 were specified, then the log would be rotated every seven days. 
            "interval": 7,
            "backupCount": 7, # Only kept last 7 days log files
            "filename": "log/debug.log",
        },
        "info": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "level": "INFO",
            "formatter": "verbose",
            "when": "D", # when='D', interval=7 were specified, then the log would be rotated every seven days. 
            "interval": 7,
            "backupCount": 7, # Only kept last 7 days log files
            "filename": "log/info.log",
        },
        "error": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "level": "ERROR",
            "formatter": "verbose",
            "when": "D", # when='D', interval=7 were specified, then the log would be rotated every seven days. 
            "interval": 7,
            "backupCount": 7, # Only kept last 7 days log files
            "filename": "log/error.log",
        },
    },
    "loggers": {
        "root": {
            "level": "DEBUG",
            "handlers": ["console"]
        },
        "django": {
            "level": "DEBUG",
            "handlers": ["debug", "info", "error"],
            "propagate": True,
            "qualname": "app"
        },
    }
}

view.py I tried below code for printing log to file but it's not working.

import logging
logger = logging.getLogger(__name__)

logger.debug('Testing')

For change print statement to logger I tried print=logger.info but not working.

  • You can create a function print.(Inside that function you can use your logger). Then where-ever you called print() your function would be called instead of the internal function. But remember this is just a work around and will work for a single python file, better to replace print with logger. – Utkarsh Dec 16 '22 at 05:36
  • import logging logger = logging.getLogger(__name__) logger.debug('Testing') @Utkarsh This one also not working for replace print – Karan Chaudhari Dec 16 '22 at 05:38

1 Answers1

0

E.g using the code as follows, using StringIO will rediect the printed information into print_str, which is a byte_string object. Before file=print_str, you can print anything as you how you usually use the print statement. any_variable_or_object can be anything, a number, list, or a object etc.

from io import StringIO
import logging
import pandas as pd
print_str = StringIO()
any_variable_or_object = pd.DataFrame()
print("the result of of any variables;", any_variable_or_object, file=print_str)
logging.info(print_str.getvalue())
XYZ
  • 352
  • 5
  • 19
  • It's only print in code like this: 2022-12-22 01:32:18,411 - django.server - ERROR - log_message:187 - "GET / HTTP/1.1" 500 77595 not printing the message – Karan Chaudhari Dec 16 '22 at 07:30
  • it seems in your log setting, the log information is printed to files. `"filename": "log/debug.log"` ..., `"filename": "log/error.log"` . Check whether the debug level information indeed goes to the file `debug.log`. Change the setting to `sys.stdout` so that make sure all level log information is printed to the console and test again. – XYZ Dec 16 '22 at 07:39
  • yes debug logs goes to file and in settings.py already mention "stream": "ext://sys.stdout" – Karan Chaudhari Dec 16 '22 at 08:11