Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share logger instance among Flask app and other classes

I have a python app where the main class is a Flask app, and when I receive a HTTP request I launch methods from other classes. I want to share the logger and apparently it should be very easy but I can't make it work.

Here is my code for the main class:

#!flask/bin/python
from flask import Flask, jsonify, abort, make_response, request
from SGRuntime import SGRuntime
import logging
from logging.handlers import TimedRotatingFileHandler

app = Flask(__name__)
sgRuntime = SGRuntime()

@app.route('/sg/api/v2.0/init', methods=['GET'])
def init_service():
    app.logger.info('Request: Init service')
    return sgRuntime.start()


@app.route('/sg/api/v2.0/stop', methods=['GET'])
def stop_service():
    app.logger.info('Request: Stop service')
    return sgRuntime.stop()


@app.route('/sg/api/v2.0/restart', methods=['GET'])
def restart_service():
    app.logger.info('Request: Restart service')
    return sgRuntime.restart()


@app.route('/sg/api/v2.0/alive', methods=['GET'])
def alive():
    if sgRuntime.running == True:
        return sgRuntime.get_stat()
    else:
        return "Service not running"

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)


if __name__ == '__main__':
    handler = TimedRotatingFileHandler('./SGLog.log', when='midnight', interval=1)
    handler.setLevel(logging.DEBUG)
    fileFormatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
    handler.setFormatter(fileFormatter)
    app.logger.addHandler(handler)
    app.run(debug=True)

And the code for my SGRuntime.py where I would like to use the same logger:

import serial
import logging

class SGRuntime():

CONFIG_FILE_PATH = "config.cfg"
running = False
configuration = {
    'port' : 'COM5',
    'baudrate' : '9600',
    'debug' : '0',
    'serverip' : '127.0.0.1',
    'serverport' : 8080
}    
protocol = None
startedSince = None

def __init__(self):
    self.running = False

def start(self):
    if self.running:

        return 'ERROR: ALREADY RUNNING'

    self.logger = logging.getLogger()
    self.logger.info('SGRuntime started')

The output of the logger is:

2016-01-21 16:20:28,137 INFO     Request: Init service

So I'm missing the logging from my SGRuntime class. Can you help me?

Thank you very much in advanced!

like image 598
cjbs Avatar asked Jan 21 '16 15:01

cjbs


1 Answers

logging.getlogger creates a logger. So in SGRuntime you create a second logger. You want to import the app.logger instance from your package and use that for logging.

An easier way to do this could be confuguring the standard logger as described in the logging how to: Logging from multiple modules. You only have to call logging.info('Your message') and it will log when the logging level is INFO or DEBUG.

like image 191
Menno Hölscher Avatar answered Oct 18 '22 19:10

Menno Hölscher