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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With