[Flask] Logging from non-flask objects

Scott Werner scott.werner.vt at gmail.com
Fri Jul 8 09:35:50 EDT 2016


Expanding on Ziirish's reply, I do the following:

import logging


class MyObject(object):

    def __init__(self, logger=None):

        self.logger = logger or logging.getLogger(__name__)

    def hello(self):

        self.logger.info('hi')


my = MyObject(logger=current_app.logger)


On Fri, Jul 8, 2016 at 5:49 AM, Ziirish <ziirish at ziirish.info> wrote:

> Hello,
>
> As usual, there is more than one way to do it.
> I don't know what is the best way to do it though so here are a few
> examples.
>
> 1. Use the current_app object. In the module defining your object you can
> do
> this:
>
> from flask import current_app
>
> class MyObject:
>     def foo(self):
>         current_app.logger.info('bar')
>
>
> 2. Like you suggested, you could pass to your object the flask app (that's
> basically what most of the flask extensions do):
>
> class MyObject:
>     def __init__(self, app=None):
>         self.app = app
>
>     def init_app(self, app):
>         self.app = app
>
>     def foo(self):
>         self.app.logger.info('bar')
>
>
> There are probably other ways but those are the two most common IMHO.
>
>
> * On Thursday, July 07, 2016 at 05:27 PM -0400, Guy Matz <
> guymatz at gmail.com> wrote:
> > Hi!  Can anyone recommend a way to log from objects that are not flask
> > objects?  I.e. if my flask code creates a new object that does some
> > processing, etc., how can I get access to the logger from that object?
> Do
> > I need to pass in the logger to the new object?  Or is there a better
> way?
> >
> > Thanks!
> > Guy
> _______________________________________________
> Flask mailing list
> Flask at python.org
> https://mail.python.org/mailman/listinfo/flask
>



-- 
Scott Werner
scott.werner.vt at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20160708/4e0f541f/attachment.html>


More information about the Flask mailing list