[OPTFRA-585] Update release notes
[optf/osdf.git] / osdf / logging / onap_common_v1 / CommonLogger_testing.py
1 #!/usr/bin/python
2
3 # -------------------------------------------------------------------------
4 #   Copyright (c) 2015-2017 AT&T Intellectual Property
5 #
6 #   Licensed under the Apache License, Version 2.0 (the "License");
7 #   you may not use this file except in compliance with the License.
8 #   You may obtain a copy of the License at
9 #
10 #       http://www.apache.org/licenses/LICENSE-2.0
11 #
12 #   Unless required by applicable law or agreed to in writing, software
13 #   distributed under the License is distributed on an "AS IS" BASIS,
14 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 #   See the License for the specific language governing permissions and
16 #   limitations under the License.
17 #
18 # -------------------------------------------------------------------------
19 #
20 """
21 Test the ONAP Common Logging library in Python.
22 CommonLogger_test.py
23 """
24
25
26 from __future__ import print_function   # for the example code below parsing command line options
27 import os, sys, getopt                  # for the example code below parsing command line options
28
29 from osdf.logging.onap_common_v1.CommonLogger import CommonLogger                     # all that is needed to import the CommonLogger library
30
31 import uuid                             # to create UUIDs for our log records
32 import time                             # to create elapsed time for our log records
33
34
35 #----- A client might want to allow specifying the configFile as a command line option
36 usage="usage: %s [ -c <configFile> ]" % ( os.path.basename(__file__) )
37 try:
38     opts, args = getopt.getopt(sys.argv[1:], "c:")
39 except getopt.GetoptError:
40     print(usage, file=sys.stderr)
41     sys.exit(2)
42
43 configFile = "CommonLogger_test.config"
44 for opt, arg in opts:
45     if opt == "-c":
46         configFile = arg
47     else:
48         print(usage, file=sys.stderr)
49         sys.exit(2)
50
51
52 #----- Instantiate the loggers
53
54 # The client's top-level program (e.g., vPRO.py) can create a unique identifier UUID to differentiate between multiple instances of itself.
55 instanceUUID = uuid.uuid1()
56
57 # The client should identify its ONAP component -- and if applicable -- its ONAP sub-component
58 serviceName = "DCAE/vPRO"
59
60 # Instantiate using a configuration file with a key specifying the log file name and set fields' default values
61 errorLog =   CommonLogger.CommonLogger(configFile, "error",   instanceUUID=instanceUUID, serviceName=serviceName)
62 metricsLog = CommonLogger.CommonLogger(configFile, "metrics", instanceUUID=instanceUUID, serviceName=serviceName)
63 auditLog =   CommonLogger.CommonLogger(configFile, "audit",   instanceUUID=instanceUUID, serviceName=serviceName)
64 debugLog =   CommonLogger.CommonLogger(configFile, "debug",   instanceUUID=instanceUUID, serviceName=serviceName)
65
66
67 #----- use the loggers
68
69 # both metrics and audit logs can have an event starting time. This only affects the next log message.
70 metricsLog.setStartRecordEvent()
71 auditLog.setStartRecordEvent()
72
73 # Simple log messages
74 debugLog.debug("a DEBUG message for the debug log")
75 metricsLog.info("an INFO message for the metrics log")
76 auditLog.info("an INFO message for the audit log")
77 errorLog.warn("a WARN message for the error log")
78 errorLog.error("an ERROR message for the error log")
79 errorLog.fatal("a FATAL message for the error log")
80
81
82 # Can override any of the other fields when writing each log record
83 debugLog.debug("demonstrating overriding all fields with atypical values", requestID="2", serviceInstanceID="3", threadID="4", serverName="5", serviceName="6", instanceUUID="7", severity="9", serverIPAddress="10", server="11", IPAddress="12", className="13", timer="14")
84
85
86 # The is an example of an interaction between two ONAP components:
87
88 # vPRO generates Closed Loop RESTful API requests to App-C, knowing this information:
89 requestClient = "netman@localdcae.att.com:~/vPRO_trinity/vPRO.py:905"  # uniquely identifies the requester
90 requestTime = "2015-08-20 20:57:14.463426"                             # unique ID of the request within the requester's scope
91 request = "Restart"
92
93 # Form the value for Common Logging's requestID field:
94 requestID = requestClient + "+" + requestTime  # vPRO will use this as the unique requestID
95 # requestID = uuid.uuid1()  # other services might generate a UUID as their requestID
96
97 # Form the value for Common Logging's serviceName field when an interaction between two ONAP components:
98 ourONAP = serviceName
99 peerONAP = "App-C"
100 operation = request
101 interaction = ourONAP + ":" + peerONAP + "." + operation
102
103 # Let's calculate and report elapsed times
104 start = time.time()
105
106 # Log the request
107 auditLog.info("Requesting %s to %s" %(peerONAP, operation), requestID=requestID, serviceName=interaction)
108
109 # Wait for first response
110 time.sleep(1)  # simulate processing the action, e.g., waiting for response from App-C
111
112 # Form the value for Common Logging's serviceName field when an interaction between two ONAP components:
113 operation = 'PENDING'
114 interaction = peerONAP + ":" + ourONAP + "." + operation
115
116 # Log the response with elapsed time
117 ms = int(round(1000 * (time.time() - start)))  # Calculate elapsed time in ms
118 auditLog.info("%s acknowledged receiving request for %s" %(peerONAP, operation), requestID=requestID, serviceName=interaction, timer=ms)
119
120 # Wait for next response
121 time.sleep(1)  # simulate processing the action, e.g., waiting for response from App-C
122
123 # Form the value for Common Logging's serviceName field when an interaction between two ONAP components:
124 operation = 'SUCCESS'
125 interaction = peerONAP + ":" + ourONAP + "." + operation
126
127 # Log the response with elapsed time
128 ms = int(round(1000 * (time.time() - start)))  # Calculate elapsed time in ms
129 auditLog.info("%s finished %s" %(peerONAP, operation), requestID=requestID, serviceName=interaction, timer=ms)
130
131
132 # Can change the fields' default values for a logger after instantiation if desired
133 debugLog.setFields(serviceName="DCAE", threadID='thread-2')
134
135 # Then subsequent logging will have the new default field values
136 debugLog.info("Something happened")
137 debugLog.warn("Something happened again")
138
139
140 # Unset (set=None) a field so the Common Logger will use the default value
141 debugLog.info("threadID should be default", threadID=None)
142 debugLog.setFields(threadID=None)
143 debugLog.info("threadID should be default")