1 # Copyright 2018 ke liang <lokyse@163.com>.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
18 from logging import config
19 from watchdog.observers import Observer
20 from watchdog.events import FileSystemEventHandler
23 __all__ = ['patch_loggingYaml']
26 def _yaml2Dict(filename):
28 with open(filename, 'rt') as f:
29 return yaml.load(f.read())
32 class FileEventHandlers(FileSystemEventHandler):
34 def __init__(self, filepath):
36 FileSystemEventHandler.__init__(self)
37 self.filepath = filepath
38 self.currentConfig = None
40 def on_modified(self, event):
42 if event.src_path == self.filepath:
43 newConfig = _yaml2Dict(self.filepath)
44 print("reload logging configure file %s" % event.src_path)
45 config.dictConfig(newConfig)
46 self.currentConfig = newConfig
50 print("Reuse the old configuration to avoid this"
51 "exception terminate program")
52 if self.currentConfig:
53 config.dictConfig(self.currentConfig)
56 def _yamlConfig(filepath=None, watchDog=None):
59 load logging configureation from yaml file and monitor file status
61 :param filepath: logging yaml configure file absolute path
62 :param watchDog: monitor yaml file identifier status
65 if os.path.isfile(filepath) is False:
66 raise OSError("wrong file")
68 dirpath = os.path.dirname(filepath)
72 dictConfig = _yaml2Dict(filepath)
73 # The watchdog could monitor yaml file status,if be modified
74 # will send a notify then we could reload logging configuration
77 event_handler = FileEventHandlers(filepath)
78 observer.schedule(event_handler=event_handler, path=dirpath,
80 observer.setDaemon(True)
83 config.dictConfig(dictConfig)
86 # here we keep the correct configuration for reusing
87 event_handler.currentConfig = dictConfig
93 def patch_loggingYaml():
94 # The patch to add yam config forlogginf and runtime
95 # reload logging when modify yaml file
96 config.yamlConfig = _yamlConfig