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.
15 from logging import LogRecord
16 from logging.handlers import SMTPHandler
17 from typing import Tuple, List, Optional, Union
19 from onaplogging.utils.system import is_above_python_2_7, is_above_python_3_2
21 from .marker import match_markers, Marker
24 class MarkerNotifyHandler(SMTPHandler):
25 """Handler for email notification.
27 Wraps logging.handler.SMTPHandler and extends it by sending only such
28 notifications which contain certain markers.
33 markers: A marker or a list of markers.
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.
48 # type: () -> Union[Marker, List[Marker]]
52 def markers(self, value):
53 # type: ( Union[Marker, List[Marker]] ) - None
57 mailhost, # type: Tuple
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]]]
67 if is_above_python_3_2():
68 super(MarkerNotifyHandler, self). \
69 __init__( # noqa: E122
78 elif is_above_python_2_7():
79 super(MarkerNotifyHandler, self). \
80 __init__( # noqa: E122
89 SMTPHandler.__init__(self,
97 self.markers = markers
99 def handle(self, record):
100 # type: (LogRecord) -> bool
102 Handle a LogRecord record. Send an email notification.
104 return self.send_notification(record)
106 def send_notification(self, record):
107 # type: (LogRecord) -> bool
108 """Email notification handler.
110 Matches the record with the specific markers set for email
111 notifications. Sends an email notification if that marker(s) matched.
114 record (LogRecord): A record that might contain a marker.
116 bool: Whether a record was passed for emission (to be sent).
119 if hasattr(self, "markers") and \
120 self.markers is None:
123 if match_markers(record, self.markers):
125 if is_above_python_2_7():
126 return super(MarkerNotifyHandler, self).handle(record)
127 return SMTPHandler.handle(self, record)