Home > Enterprise >  Logger not creating logs on log file in flask application;
Logger not creating logs on log file in flask application;

Time:10-20

I want to create logs in my log file, logs can be shown on the terminal but not written on the log files. I created a package imp_calc which has templates and other files inside it, accessing it using run.py which accesses the imp_calc package's modules. My folder structure is as follows:

impurity_calculator_app
  ├── files
  ├── templates
  ├── static
  ├── imp_calc
  |   ├── __init__.py
  |   ├── models.py
  |   ├── forms.py
  |   └── routes.py
  ├─ instance
  ├─ record.log
  └─ run.py

my init.py file

#__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
import logging

logging.basicConfig(filename='record.log', level=logging.DEBUG)
logger = logging.getLogger('imp_calc')
logger.setLevel(logging.INFO)

app = Flask(__name__)
app.debug = True

#app.config['SECRET_KEY'] = 'AntheaPharma*01'
# Setting up my database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SECRET_KEY'] = '0b843376d6f247b8a5e38df2'
#creating a sqlalchemy instance
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)

login_manager.login_view = "login_page"
login_manager.login_message_category = "info"
from imp_calc import routes

My Routes Folder through which I want to throw my logs

#routes.py
import logging
from logging import INFO
logger = logging.getLogger('imp_calc')

@app.route('/')
def home():
    app.logger.info('Called hello_world!')
    return render_template('index.html')

my run.py

#run.py
from imp_calc import app

if __name__ == '__main__':
    app.run(debug=False)

CodePudding user response:

You are using app.logger inside route. But basicConfig does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger.

You can use dictConfig to configure loggers / handlers / formatters. Here is an example:

from flask import Flask
import logging

dictConfig({
    'version': 1,
    'loggers': {
        # root logger
        '': {
            'level': 'INFO',
            'handlers': ['console_handler'],
        },
        'imp_calc': {
            'level': 'INFO',
            'handlers': ['console_handler'],
            'propagate': False,
        },
        # this logger will write logs into file
        'debug': {
            'level': 'INFO',
            'handlers': ['console_handler', 'file_handler'],
            'propagate': False,
        },
    },
    'handlers': {
        'console_handler': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'stream': 'ext://sys.stdout',
            'formatter': 'simple'
        },
        'file_handler': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'debug.log',
            'maxBytes': 1024,
            'backupCount': 3,
            'formatter': 'simple',
        }
    },
    'formatters': {
        'simple': {
            'format': '%(pathname)s:%(lineno)d %(name)s %(asctime)s - %(levelname)s - %(message)s',
        },
    },
})

app = Flask(__name__)


@app.route('/')
def home():
    logging.getLogger().info('log from root logger')
    logging.getLogger('imp_calc').info('log from imp_calc logger')
    app.logger.info('log from app logger')
    return 'ok'


if __name__ == '__main__':
    app.run(debug=True, host='localhost')

Open http://localhost:5000/. You'll see stdout logs:

../debug.py:87 root 2022-10-17 15:31:09,242 - INFO - log from root logger
../debug.py:88 imp_calc 2022-10-17 15:31:09,243 - INFO - log from imp_calc logger
../debug.py:89 debug 2022-10-17 15:31:09,243 - INFO - log from app logger

Let's check file logs(cat debug.log):

../debug.py:89 debug 2022-10-17 15:31:09,243 - INFO - log from app logger

So just use dictConfig.

  • Related