f93dd12a13a710800a39fadbe774fbd2c3c22a69
[logging-analytics.git] / pylog / onaplogging / logWatchDog.py
1 # Copyright 2018 ke liang <lokyse@163.com>.
2 #
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
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 import os
16 import yaml
17 import traceback
18 from logging import config
19 from watchdog.observers import Observer
20 from watchdog.events import FileSystemEventHandler
21
22
23 __all__ = ['patch_loggingYaml']
24
25
26 def _yaml2Dict(filename):
27
28     with open(filename, 'rt') as f:
29         return yaml.load(f.read())
30
31
32 class FileEventHandlers(FileSystemEventHandler):
33
34     def __init__(self, filepath):
35
36         FileSystemEventHandler.__init__(self)
37         self.filepath = filepath
38         self.currentConfig = None
39
40     def on_modified(self, event):
41         try:
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
47
48         except Exception:
49             traceback.print_exc()
50             print("Reuse the old configuration to avoid this"
51                   "exception terminate program")
52             if self.currentConfig:
53                 config.dictConfig(self.currentConfig)
54
55
56 def _yamlConfig(filepath=None, watchDog=None):
57
58     """
59     load logging configureation from yaml file and monitor file status
60
61     :param filepath: logging yaml configure file absolute path
62     :param watchDog: monitor yaml file identifier status
63     :return:
64     """
65     if os.path.isfile(filepath) is False:
66         raise OSError("wrong file")
67
68     dirpath = os.path.dirname(filepath)
69     event_handler = None
70
71     try:
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
75         if watchDog:
76             observer = Observer()
77             event_handler = FileEventHandlers(filepath)
78             observer.schedule(event_handler=event_handler, path=dirpath,
79                               recursive=False)
80             observer.setDaemon(True)
81             observer.start()
82
83         config.dictConfig(dictConfig)
84
85         if event_handler:
86             # here we keep the correct configuration for reusing
87             event_handler.currentConfig = dictConfig
88
89     except Exception:
90         traceback.print_exc()
91
92
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