[Flask] Logging from non-flask objects

Guy Matz guymatz at gmail.com
Mon Jul 11 10:51:46 EDT 2016


Silly me.  I am creating a flask app that uses celery, so I actually needed
the logger from celery in this case.  Sorry for the bother!

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

> Well, the error speaks for itself.
>
> How is your object instantiated/called in your application?
>
>
>
> * On Friday, July 08, 2016 at 11:22 AM -0400, Guy Matz <guymatz at gmail.com>
> wrote:
> > Thanks!  So I tried something like this:
> >
> > from flask import current_app
> > class MyObject:
> >   def __init__(self):
> >     self.logger = current_app.logger
> >     self.logger.info('sdfdf")
> >
> > And now I'm getting something like this:
> > ERROR/MainProcess] Task
> > main.async_process_on_startup[27608e0c-c9a5-4ef0-ac47-244759acd465]
> raised
> > unexpected: RuntimeError('Working outside of application context.\n\nThis
> > typically means that you attempted to use functionality that needed\nto
> > interface with the current application object in a way.  To solve\nthis
> set
> > up an application context with app.app_context().  See the\ndocumentation
> > for more information.',)
> >
> > Any idea what I did wrong?
> >
> > Thanks again!!
> >
> > 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
> > >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20160711/75856e03/attachment.html>


More information about the Flask mailing list