1 # Copyright (c) 2018 VMware, Inc.
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.
16 from logging import config
17 from watchdog.observers import Observer
18 from watchdog.events import FileSystemEventHandler
21 __all__ = ['patch_loggingYaml']
24 def _yaml2Dict(filename):
26 with open(filename, 'rt') as f:
27 return yaml.load(f.read())
30 class FileEventHandlers(FileSystemEventHandler):
32 def __init__(self, filepath):
34 FileSystemEventHandler.__init__(self)
35 self.filepath = filepath
36 self.currentConfig = None
38 def on_modified(self, event):
40 if event.src_path == self.filepath:
41 newConfig = _yaml2Dict(self.filepath)
42 print ("reload logging configure file %s" % event.src_path)
43 config.dictConfig(newConfig)
44 self.currentConfig = newConfig
46 except Exception as e:
47 traceback.print_exc(e)
48 print ("Reuse the old configuration to avoid this "
49 "exception terminate program")
50 if self.currentConfig:
51 config.dictConfig(self.currentConfig)
54 def _yamlConfig(filepath=None, watchDog=None):
57 load logging configureation from yaml file and monitor file status
59 :param filepath: logging yaml configure file absolute path
60 :param watchDog: monitor yaml file identifier status
63 if os.path.isfile(filepath) is False:
64 raise OSError("wrong file")
66 dirpath = os.path.dirname(filepath)
70 dictConfig = _yaml2Dict(filepath)
71 # The watchdog could monitor yaml file status,if be modified
72 # will send a notify then we could reload logging configuration
75 event_handler = FileEventHandlers(filepath)
76 observer.schedule(event_handler=event_handler, path=dirpath,
78 observer.setDaemon(True)
81 config.dictConfig(dictConfig)
84 # here we keep the correct configuration for reusing
85 event_handler.currentConfig = dictConfig
87 except Exception as e:
88 traceback.print_exc(e)
91 def patch_loggingYaml():
93 # The patch to add yam config forlogginf and runtime
94 # reload logging when modify yaml file
95 config.yamlConfig = _yamlConfig