SoFunction
Updated on 2024-11-19

Tutorials on using Python's

When using the peewee framework, log messages do not appear by default.

from peewee import Model, CharField, DateTimeField, IntegerField
from peewee_mssql import MssqlDatabase
db = MssqlDatabase(database='test', host='.', user='sa', password='sa')
class BaseModel(Model):
 class Meta:
  database = db
class Person(BaseModel):
 Name = CharField(verbose_name='Name', max_length=20)
 Age = IntegerField(verbose_name='Age')
 Birthday = DateTimeField(verbose_name='Birthday', null=True)
p = Person(Name='Zhang San', Age='20', Birthday='2018-01-01')
()

We add a log definition to the code above:

import logging
logger = ('peewee')
()
(())

The magic happens, and running the program hits a line of logs:

We didn't write any logs even though we defined them, so where did this line of logs come from?

Looking at the source code for peewee, I see that there is a definition for logging:

Most of the explanations on the web are one sentence: the Handler instance ignores error messages, and is often used by library developers who want to use logging to avoid 'No handlers could be found for logger XXX' messages.

It doesn't make sense at first glance, but when you think about it, it's actually quite simple.(name) method is to use a factory method to return a logger instance, or if a logger named name already exists, to return it directly.

In peewee, a logger named "peewee" is defined, but it is only given a NullHandler.logger = ('peewee'),This sentence actually takes the logger defined in peewee and adds a StreamHandler to it, which naturally outputs logs. Don't believe me? Change the name of the logger in your own code and see if it still outputs logs.

We can also define a NullHandler this way when we write a library, leaving the implementation up to the person who calls it.

summarize

The above is a small introduction to the use of Python in the tutorial, I hope to help you, if you have any questions please leave me a message, I will promptly reply to you. Here also thank you very much for your support of my website!