Submit python logging library seed code
[logging-analytics.git] / pylog / onaplogging / logWatchDog.py
1 # Copyright (c) 2018 VMware, Inc.
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
13 import os
14 import yaml
15 import traceback
16 from logging import config
17 from watchdog.observers import Observer
18 from watchdog.events import FileSystemEventHandler
19
20
21 __all__ = ['patch_loggingYaml']
22
23
24 def _yaml2Dict(filename):
25
26     with open(filename, 'rt') as f:
27         return yaml.load(f.read())
28
29
30 class FileEventHandlers(FileSystemEventHandler):
31
32     def __init__(self, filepath):
33
34         FileSystemEventHandler.__init__(self)
35         self.filepath = filepath
36         self.currentConfig = None
37
38     def on_modified(self, event):
39         try:
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
45
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)
52
53
54 def _yamlConfig(filepath=None, watchDog=None):
55
56     """
57     load logging configureation from yaml file and monitor file status
58
59     :param filepath: logging yaml configure file absolute path
60     :param watchDog: monitor yaml file identifier status
61     :return:
62     """
63     if os.path.isfile(filepath) is False:
64         raise OSError("wrong file")
65
66     dirpath = os.path.dirname(filepath)
67     event_handler = None
68
69     try:
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
73         if watchDog:
74             observer = Observer()
75             event_handler = FileEventHandlers(filepath)
76             observer.schedule(event_handler=event_handler, path=dirpath,
77                               recursive=False)
78             observer.setDaemon(True)
79             observer.start()
80
81         config.dictConfig(dictConfig)
82
83         if event_handler:
84             # here we keep the correct configuration for reusing
85             event_handler.currentConfig = dictConfig
86
87     except Exception as e:
88         traceback.print_exc(e)
89
90
91 def patch_loggingYaml():
92
93     # The patch to add yam config forlogginf and runtime
94     # reload logging when modify yaml file
95     config.yamlConfig = _yamlConfig