36934a83c0b3b5f3ecc80769ee3f10c3f6f2d1b2
[logging-analytics.git] / pylog / onaplogging / marker / markerHandler.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 from logging import LogRecord
16 from logging.handlers import SMTPHandler
17 from typing import Tuple, List, Optional, Union
18
19 from onaplogging.utils.system import is_above_python_2_7, is_above_python_3_2
20
21 from .marker import match_markers, Marker
22
23
24 class MarkerNotifyHandler(SMTPHandler):
25     """Handler for email notification.
26
27     Wraps logging.handler.SMTPHandler and extends it by sending only such
28     notifications which contain certain markers.
29
30     Extends:
31         SMTPHandler
32     Property:
33         markers: A marker or a list of markers.
34     Args:
35         mailhost: A (host, port) tuple.
36         fromaddr: The sender of the email notification.
37         toaddrs: Email notification recepient(s).
38         subject: Email subject.
39         credentials: A (username, password) tuple.
40         secure: For example (TLS). It is used when the
41                                   credentials are supplied.
42         timout: Default is 5.0 seconds. Python version 3.2+
43         markers: A marker or a list of markers.
44     """
45
46     @property
47     def markers(self):
48         # type: () -> Union[Marker, List[Marker]]
49         return self._markers
50
51     @markers.setter
52     def markers(self, value):
53         # type: ( Union[Marker, List[Marker]] ) - None
54         self._markers = value
55
56     def __init__(self,
57                  mailhost,          # type: Tuple
58                  fromaddr,          # type: str
59                  toaddrs,           # type: Union[List[str], str]
60                  subject,           # type: Tuple
61                  credentials=None,  # type: Tuple
62                  secure=None,       # type: Optional[Tuple]
63                  timeout=5.0,       # type: Optional[float]
64                  markers=None     # type: Optional[Union[Marker, List[Marker]]]
65                  ):
66
67         if is_above_python_3_2():
68             super(MarkerNotifyHandler, self). \
69             __init__(  # noqa: E122
70                 mailhost,
71                 fromaddr,
72                 toaddrs,
73                 subject,
74                 credentials,
75                 secure,
76                 timeout)
77
78         elif is_above_python_2_7():
79             super(MarkerNotifyHandler, self). \
80             __init__(  # noqa: E122
81                 mailhost,
82                 fromaddr,
83                 toaddrs,
84                 subject,
85                 credentials,
86                 secure)
87
88         else:
89             SMTPHandler.__init__(self,
90                                  mailhost,
91                                  fromaddr,
92                                  toaddrs,
93                                  subject,
94                                  credentials,
95                                  secure)
96
97         self.markers = markers
98
99     def handle(self, record):
100         # type: (LogRecord) -> bool
101         """
102         Handle a LogRecord record. Send an email notification.
103         """
104         return self.send_notification(record)
105
106     def send_notification(self, record):
107         # type: (LogRecord) -> bool
108         """Email notification handler.
109
110         Matches the record with the specific markers set for email
111         notifications. Sends an email notification if that marker(s) matched.
112
113         Args:
114             record (LogRecord): A record that might contain a marker.
115         Returns:
116             bool: Whether a record was passed for emission (to be sent).
117         """
118
119         if  hasattr(self, "markers") and \
120             self.markers is None:
121             return False
122
123         if match_markers(record, self.markers):
124
125             if is_above_python_2_7():
126                 return super(MarkerNotifyHandler, self).handle(record)
127             return SMTPHandler.handle(self, record)
128
129         return False