19. The use of packet logging

package

What is the package: --- folder is a file with a package __init__.py

Recommended from. Import

Introducing the package;

  1. from ss.bake.api.policy import func --- absolute imports
  2. from ..api.www import ww ww () --- relative path must be introduced externally

important point:

  1. Using a relative path must be introduced into the outermost layer packets peer
  2. python2 the import package, if the package is not __init__.py will complain, ython3 no __init__.py without error

As long as the folder containing the file __init__.py is a package, the package is doing it?

Recall that before we did not learn a whole module when the function is written to a file in order to fully reuse will be a feature we use the module, but the module will be more and more slowly. We want to improve the structural program maintainability, on the use of the package will be unified management module

Package can manage multiple modules, which we want to use the bag how to do it?

Using the import and from xx import xx conventional structure

bake            

    ├── __init__.py       

    ├── api               

        ├── __init__.py

        ├── policy.py

        └── versions.py

  ├── cmd             

    ├── __init__.py

    └── manage.py

  └── db                

      ├── __init__.py

      └── models.py

We create a test.py import policy.py we use the import module of the same level in the bake time can only be added to the Road King api sys.path, we take a look at the package using import import

import bake.api.policy
bake.api.policy.get()

Imported too long when used below also need to write it again repeat, we can use as surnamed

import bake.api.policy as p
p.get()

Such operations only support package, ordinary folders invalid, someone must be thinking I have to take over and then bake layers of open tools that take on it

import bake
bake.api.policy.get()

To do so, so that the import is only the policy introduced, how would someone want to pack all the modules under api import Do not worry, saying the way alone imported

You can use import to import, take a look at the way from the import

from bake.api import policy
policy.get()
from bake import api
print(api.versions.name)

Or not make, by the two us to feel content when they are imported to be imported, the import can not be performed to open the box

We are talking about a separate import module for the Road now says how import all modules in a package, you want to import all the modules in a package we need to do hands and feet in the package __init__.py

bake包下的__init__.py
from . import api

Is the current path, because from the time can not be empty

api包下的__init__.py
from . import policy

We will __init__ configured in a package, and then import test.py

import bake
bake.api.policy.get()

So good, and this is why? We import import bake this package, because the bake is a folder can not carry out any operation, instead of let it go __init__.py import this package module api, api also a file folder can not operate on the need to make __init__.py api api go below the bottom of the two modules

The company and the superior-subordinate relationship, like the analogy test.py is now a ceo to this small staff and policy talk, ceo put this idea personnel manager, personnel manager is to bake the package, the personnel manager to inform the personnel to make personnel to find what policy in that department, personnel department found the head of notification, the person in charge of the department in charge of the department notice, policy director told the staff, said ceo looking for you, go to authorities with the personnel policy, personnel policy with personnel then go in with a policy ceo. the last successful and ceo were some exchanges

If the time to convey the middle of a forgotten part of the transfer, policy not know ceo looking for him, ceo waited a long time without being given to angry ceo

When used to note: Some students want to import versions is used directly import, use the policy file is no problem, very beautiful, very happy in the policy document but when test.py performed'll get an error because we test. import versions .py performed the equivalent in test.py file search, certainly will not find, we need to add to the current Road King sys.path in the policy document will be able to do the following:

import os
import sys
sys.path.insert(os.path.dirname(__file__)

__file__ acquisition is the path to the current file, so that we will be able to test in normal use, we can use from the next a package all modules such as we all now want to import all the modules in the package will need to import cmd in the packet bake init set .py

from . import *

We need to set __init__.py in package api

__all__ = ["policy","versions"]
或
from . import policy
from . import versions

We need to set __init__.py in package db

__all__ = ["models"]
或
from . import models

We need to set __init__.py in package cmd

__all__ = ["manage"]
或
from . import manage

Under the above two recommended from. Import manage flexible, high readability

test.py call as follows:

from bake.api import *
print(versions.name)
policy.get()

from bake.db import *
models.register_models(123)

from bake.cmd import *
print(manage.name)

In use the import points have noted, if the import python2 packet, the error will not __init__.py file to python3 no package __init__.py import file import no error packet from the packet or modules (not performing the import behind. operating)

Path: absolute path: (bake) package from the outermost look is an absolute path relative path: the path is relative, .. is the parent directory for example: we want to import bake in bake / api / version.py in /cmd/manage.py

# 绝对路径:
from bake.cmd import manage
manage.main()

#相对路径:
from ..cmd import manage
manage.main()

Note that when using a relative path must be at the same level that bake test files we need to test and bake at the same level in test.py

from bake.cmd import manage

logging log

Us about the function of this logging module that is to record the various states of our software, you are now, and I find the icon with spider mites, then right look for the error log is not there. In fact, every software there is an error log, developers can modify his program through the contents of the error log

This is just an application scenario, some will be used to log transactions. For example, you give me transfer record should do it,

We use a credit card, a sum will be recorded for each consumer, we look at how to use this log?

We first look at the functional configuration simple

import logging  
logging.debug('debug message')  
logging.info('info message')  
logging.warning('warning message')  
logging.error('error message')  
logging.critical('critical message')

Python logging module logs the default print to standard output, and only shows a greater than or equal WARNING level logging, logging level indicating that the default to WARNING

(Log level grade CRITICAL> ERROR> WARNING> INFO> DEBUG),

The default log format for the log level: Logger Name: User output messages.

We write this function themselves with normal use, but is not flexible enough, we look at this flexible

Flexible configuration log level, the log format, output location:

import logging  
logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  
                    datefmt='%a, %d %b %Y %H:%M:%S',  
                    filename='test.log',  
                    filemode='w')  

logging.debug('debug message')  
logging.info('info message')  
logging.warning('warning message')  
logging.error('error message')  
logging.critical('critical message')

basicConfig () function can be changed by the logging module specific parameters default behavior parameters are available:

  • filename: Creating FiledHandler, such logs are stored in the specified file with the specified file name.
  • filemode: File Open, this parameter is specified in the filename, the default value "a" may also be designated as "w".
  • format: log handler specified display format.
  • datefmt: specify the date and time format.
  • Set logging levels: level
  • stream: Creating StreamHandler with the specified stream. You can specify output to
  • sys.stderr, sys.stdout or file (f = open ( 'test.log', 'w')), default sys.stderr. If both lists the filename and stream two parameters, the stream parameter is ignored.

the format parameter string format may be used :

  • % (Name) s Logger name
  • % (Levelno) s log level digital form
  • % (Levelname) s log level text form
  • % (Pathname) s call to the full path name of the log output function module may not
  • % (Filename) s call log output function module filename
  • % (Module) s call log output function module name
  • Function names% (funcName) s call log output function
  • OK code statements% (lineno) d log output function call where
  • % (Created) f the current time, represented by a standard floating point representation UNIX Time
  • Since the number of milliseconds Logger created when the d output log information% (relativeCreated)
  • % (Asctime) of the current time string s. The default format is "2003-07-0816: 49: 45,896." Milliseconds after the comma
  • % (Thread) d thread ID. Maybe not
  • % (ThreadName) s thread name. Maybe not
  • % (Process) d process ID. Maybe not
  • Message% (message) s user output

logger object configuration

import logging

logger = logging.getLogger()
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler('test.log',mode="a",encoding='utf-8') 

# 再创建一个handler,用于输出到控制台 
ch = logging.StreamHandler() #屏幕
formatter = logging.Formatter('%(asctime)s - %(name)s - %(filename)s-[line:%(lineno)d]%(levelname)s - %(message)s')#--将屏幕和文件都用以上格式

fh.setLevel(logging.DEBUG)#设置记录级别

fh.setFormatter(formatter) 
#  使用自己定义的格式化内容
ch.setFormatter(formatter) 

logger.addHandler(fh) #logger对象可以添加多个fh和ch对象 
logger.addHandler(ch) 

logger.debug('logger debug message') 
logger.info('logger info message') 
logger.warning('logger warning message') 
logger.error('logger error message') 
logger.critical('logger critical message')

logging library provides a number of components: Logger, Handler, Filter, Formatter. Logger object provides an interface application can be used directly, Handler send logs to the appropriate destination, Filter provides a method of filtering log information, Formatter display format specified log. Further, by: logger.setLevel (logging.Debug) set the level, of course, can also

fh.setLevel (logging.Debug) set a single-file stream level.

Guess you like

Origin www.cnblogs.com/changxin7/p/11278603.html