4
4
import sys
5
5
from logging .handlers import RotatingFileHandler
6
6
from pathlib import Path
7
+ from typing import Any , Optional , Union
7
8
8
9
from demisto_sdk .commands .common .content_constant_paths import CONTENT_PATH
9
10
from demisto_sdk .commands .common .tools import string_to_bool
25
26
DATE_FORMAT = "%Y-%m-%dT%H:%M:%S"
26
27
27
28
DEPRECATED_PARAMETERS = {
28
- "-v" : "--console-log-threshold or --file-log-threshold " ,
29
- "-vv" : "--console-log-threshold or --file-log-threshold " ,
30
- "-vvv" : "--console-log-threshold or --file-log-threshold " ,
31
- "--verbose" : "--console-log-threshold or --file-log-threshold " ,
32
- "-q" : "--console-log-threshold or --file-log-threshold " ,
33
- "--quiet" : "--console-log-threshold or --file-log-threshold " ,
34
- "-ln" : "--log-path " ,
35
- "--log-name" : "--log-path " ,
36
- "no_logging" : "--console-log-threshold or --file-log-threshold " ,
29
+ "-v" : "--console_log_threshold or --file_log_threshold " ,
30
+ "-vv" : "--console_log_threshold or --file_log_threshold " ,
31
+ "-vvv" : "--console_log_threshold or --file_log_threshold " ,
32
+ "--verbose" : "--console_log_threshold or --file_log_threshold " ,
33
+ "-q" : "--console_log_threshold or --file_log_threshold " ,
34
+ "--quiet" : "--console_log_threshold or --file_log_threshold " ,
35
+ "-ln" : "--log_file_path " ,
36
+ "--log-name" : "--log_file_path " ,
37
+ "no_logging" : "--console_log_threshold or --file_log_threshold " ,
37
38
}
38
39
40
+
41
+ def parse_int_or_default (value : Any , default : int ) -> int :
42
+ """
43
+ Parse int or return default value
44
+ Args:
45
+ value: value to parse
46
+ default: default value to return if parsing failed
47
+
48
+ Returns:
49
+ int: parsed value or default value
50
+
51
+ """
52
+ try :
53
+ return int (value )
54
+ except (ValueError , TypeError ):
55
+ return default
56
+
57
+
39
58
SUCCESS_LEVEL : int = 25
59
+ DEMISTO_SDK_LOG_FILE_SIZE = parse_int_or_default (
60
+ os .getenv ("DEMISTO_SDK_LOG_FILE_SIZE" ), 1_048_576 # 1MB
61
+ )
62
+ DEMISTO_SDK_LOG_FILE_COUNT = parse_int_or_default (
63
+ os .getenv ("DEMISTO_SDK_LOG_FILE_COUNT" ), 10
64
+ )
40
65
41
66
42
67
def handle_deprecated_args (input_args ):
@@ -97,10 +122,14 @@ def handle_deprecated_args(input_args):
97
122
98
123
99
124
def get_handler_by_name (logger : logging .Logger , handler_name : str ):
100
- for current_handler in logger .handlers :
101
- if current_handler .get_name == handler_name :
102
- return current_handler
103
- return None
125
+ return next (
126
+ (
127
+ current_handler
128
+ for current_handler in logger .handlers
129
+ if current_handler .get_name == handler_name
130
+ ),
131
+ None ,
132
+ )
104
133
105
134
106
135
def set_demisto_logger (demisto_logger : logging .Logger ):
@@ -124,7 +153,7 @@ def _add_logging_level(
124
153
`logging` module or if the method name is already present
125
154
Example
126
155
-------
127
- >>> addLoggingLevel ('TRACE', logging.DEBUG - 5)
156
+ >>> _add_logging_level ('TRACE', logging.DEBUG - 5)
128
157
>>> logging.getLogger(__name__).setLevel("TRACE")
129
158
>>> logging.getLogger(__name__).trace('that worked')
130
159
>>> logging.trace('so did this')
@@ -144,17 +173,17 @@ def _add_logging_level(
144
173
# This method was inspired by the answers to Stack Overflow post
145
174
# http://stackoverflow.com/q/2183233/2988730, especially
146
175
# http://stackoverflow.com/a/13638084/2988730
147
- def logForLevel (self , message , * args , ** kwargs ):
176
+ def log_for_level (self , message , * args , ** kwargs ):
148
177
if self .isEnabledFor (level_num ):
149
178
self ._log (level_num , message , args , ** kwargs )
150
179
151
- def logToRoot (message , * args , ** kwargs ):
180
+ def log_to_root (message , * args , ** kwargs ):
152
181
logging .log (level_num , message , * args , ** kwargs )
153
182
154
183
logging .addLevelName (level_num , level_name )
155
184
setattr (logging , level_name , level_num )
156
- setattr (logging .getLoggerClass (), method_name , logForLevel )
157
- setattr (logging , method_name , logToRoot )
185
+ setattr (logging .getLoggerClass (), method_name , log_for_level )
186
+ setattr (logging , method_name , log_to_root )
158
187
159
188
160
189
class ColorConsoleFormatter (logging .Formatter ):
@@ -180,10 +209,7 @@ def __init__(
180
209
@staticmethod
181
210
def _record_contains_escapes (record : logging .LogRecord ) -> bool :
182
211
message = record .getMessage ()
183
- for key in escapes :
184
- if not key .startswith ("[/]" ) and key in message :
185
- return True
186
- return False
212
+ return any (not key .startswith ("[/]" ) and key in message for key in escapes )
187
213
188
214
@staticmethod
189
215
def _string_starts_with_escapes (string : str ) -> bool :
@@ -203,7 +229,7 @@ def _get_start_escapes(record: logging.LogRecord) -> str:
203
229
while ColorConsoleFormatter ._string_starts_with_escapes (current_message ):
204
230
205
231
# Record starts with escapes - Extract them
206
- current_escape = current_message [0 : current_message .find ("]" ) + 1 ]
232
+ current_escape = current_message [: current_message .find ("]" ) + 1 ]
207
233
ret_value += current_escape
208
234
current_message = current_message [
209
235
len (current_escape ) : current_message .find ("]" , len (current_escape )) + 1
@@ -263,16 +289,17 @@ def replace_escapes(self, message):
263
289
264
290
265
291
def logging_setup (
266
- console_log_threshold = logging .INFO ,
267
- file_log_threshold = logging .DEBUG ,
268
- log_file_path = LOG_FILE_PATH ,
292
+ console_log_threshold : Union [ int , str ] = logging .INFO ,
293
+ file_log_threshold : Union [ int , str ] = logging .DEBUG ,
294
+ log_file_path : Optional [ Union [ str , Path ]] = LOG_FILE_PATH ,
269
295
) -> logging .Logger :
270
296
"""Init logger object for logging in demisto-sdk
271
297
For more info - https://docs.python.org/3/library/logging.html
272
298
273
299
Args:
274
- console_log_threshold(int): Minimum console log threshold. Defaults to logging.INFO
275
- file_log_threshold(int): Minimum console log threshold. Defaults to logging.INFO
300
+ console_log_threshold: Minimum console log threshold. Defaults to logging.INFO
301
+ file_log_threshold: Minimum console log threshold. Defaults to logging.INFO
302
+ log_file_path: Path to log file. Defaults to LOG_FILE_PATH
276
303
277
304
Returns:
278
305
logging.Logger: logger object
@@ -287,24 +314,22 @@ def logging_setup(
287
314
288
315
console_handler = logging .StreamHandler ()
289
316
console_handler .set_name (CONSOLE_HANDLER )
290
- console_handler .setLevel (
291
- console_log_threshold if console_log_threshold else logging .INFO
292
- )
317
+ console_handler .setLevel (console_log_threshold or logging .INFO )
293
318
294
319
if custom_log_path := os .getenv ("DEMISTO_SDK_LOG_FILE_PATH" ):
295
320
current_log_file_path = Path (custom_log_path )
296
321
else :
297
- current_log_file_path = log_file_path or LOG_FILE_PATH
298
- if Path ( current_log_file_path ) .is_dir ():
322
+ current_log_file_path = Path ( log_file_path or LOG_FILE_PATH )
323
+ if current_log_file_path .is_dir ():
299
324
current_log_file_path = current_log_file_path / LOG_FILE_NAME
300
325
file_handler = RotatingFileHandler (
301
326
filename = current_log_file_path ,
302
327
mode = "a" ,
303
- maxBytes = 1048576 ,
304
- backupCount = 10 ,
328
+ maxBytes = DEMISTO_SDK_LOG_FILE_SIZE ,
329
+ backupCount = DEMISTO_SDK_LOG_FILE_COUNT ,
305
330
)
306
331
file_handler .set_name (FILE_HANDLER )
307
- file_handler .setLevel (file_log_threshold if file_log_threshold else logging .DEBUG )
332
+ file_handler .setLevel (file_log_threshold or logging .DEBUG )
308
333
309
334
if string_to_bool (os .getenv ("DEMISTO_SDK_LOG_NO_COLORS" , "False" )):
310
335
console_handler .setFormatter (fmt = NoColorFileFormatter ())
@@ -335,9 +360,10 @@ def logging_setup(
335
360
demisto_logger .debug (f"Platform: { platform .system ()} " )
336
361
337
362
if not log_file_name_notified :
338
- demisto_logger .info (
339
- f"[yellow]Log file location: { current_log_file_path } [/yellow]"
340
- )
363
+ if string_to_bool (os .getenv ("DEMISTO_SDK_LOG_NOTIFY_PATH" , "True" )):
364
+ demisto_logger .info (
365
+ f"[yellow]Log file location: { current_log_file_path } [/yellow]"
366
+ )
341
367
log_file_name_notified = True
342
368
343
369
logger = demisto_logger
0 commit comments