forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
629 lines (553 loc) · 28.3 KB
/
Copy pathindex.html
File metadata and controls
629 lines (553 loc) · 28.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.7.5" />
<title>aws_lambda_powertools.logging API documentation</title>
<meta name="description" content="Logging utility" />
<link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css' rel='stylesheet'>
<link href='https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/8.0.0/sanitize.min.css' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" rel="stylesheet">
<style>.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{font-weight:bold}#index h4 + ul{margin-bottom:.6em}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>aws_lambda_powertools.logging</code></h1>
</header>
<section id="section-intro">
<p>Logging utility</p>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">"""Logging utility
"""
from .logger import Logger
__all__ = ["Logger"]</code></pre>
</details>
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="aws_lambda_powertools.logging.exceptions" href="exceptions.html">aws_lambda_powertools.logging.exceptions</a></code></dt>
<dd>
<section class="desc"></section>
</dd>
<dt><code class="name"><a title="aws_lambda_powertools.logging.filters" href="filters.html">aws_lambda_powertools.logging.filters</a></code></dt>
<dd>
<section class="desc"></section>
</dd>
<dt><code class="name"><a title="aws_lambda_powertools.logging.formatter" href="formatter.html">aws_lambda_powertools.logging.formatter</a></code></dt>
<dd>
<section class="desc"></section>
</dd>
<dt><code class="name"><a title="aws_lambda_powertools.logging.lambda_context" href="lambda_context.html">aws_lambda_powertools.logging.lambda_context</a></code></dt>
<dd>
<section class="desc"></section>
</dd>
<dt><code class="name"><a title="aws_lambda_powertools.logging.logger" href="logger.html">aws_lambda_powertools.logging.logger</a></code></dt>
<dd>
<section class="desc"></section>
</dd>
</dl>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="aws_lambda_powertools.logging.Logger"><code class="flex name class">
<span>class <span class="ident">Logger</span></span>
<span>(</span><span>service=None, level=None, child=False, sampling_rate=None, stream=None, **kwargs)</span>
</code></dt>
<dd>
<section class="desc"><p>Creates and setups a logger to format statements in JSON.</p>
<p>Includes service name and any additional key=value into logs
It also accepts both service name or level explicitly via env vars</p>
<h2 id="environment-variables">Environment variables</h2>
<dl>
<dt><strong><code>POWERTOOLS_SERVICE_NAME</code></strong> : <code>str</code></dt>
<dd>service name</dd>
<dt><strong><code>LOG_LEVEL</code></strong> : <code>str</code></dt>
<dd>logging level (e.g. INFO, DEBUG)</dd>
<dt><strong><code>POWERTOOLS_LOGGER_SAMPLE_RATE</code></strong> : <code>float</code></dt>
<dd>samping rate ranging from 0 to 1, 1 being 100% sampling</dd>
</dl>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>service</code></strong> : <code>str</code>, optional</dt>
<dd>service name to be appended in logs, by default "service_undefined"</dd>
<dt><strong><code>level</code></strong> : <code>str</code>, <code>int</code> optional</dt>
<dd>logging.level, by default "INFO"</dd>
<dt><strong><code>child</code></strong> : <code>bool</code>, optional</dt>
<dd>create a child Logger named <service>.<caller_file_name>, False by default</dd>
<dt><strong><code>sample_rate</code></strong> : <code>float</code>, optional</dt>
<dd>sample rate for debug calls within execution context defaults to 0.0</dd>
<dt><strong><code>stream</code></strong> : <code>sys.stdout</code>, optional</dt>
<dd>valid output for a logging stream, by default sys.stdout</dd>
</dl>
<h2 id="example">Example</h2>
<p><strong>Setups structured logging in JSON for Lambda functions with explicit service name</strong></p>
<pre><code>>>> from aws_lambda_powertools import Logger
>>> logger = Logger(service="payment")
>>>
>>> def handler(event, context):
logger.info("Hello")
</code></pre>
<p><strong>Setups structured logging in JSON for Lambda functions using env vars</strong></p>
<pre><code>$ export POWERTOOLS_SERVICE_NAME="payment"
$ export POWERTOOLS_LOGGER_SAMPLE_RATE=0.01 # 1% debug sampling
>>> from aws_lambda_powertools import Logger
>>> logger = Logger()
>>>
>>> def handler(event, context):
logger.info("Hello")
</code></pre>
<p><strong>Append payment_id to previously setup logger</strong></p>
<pre><code>>>> from aws_lambda_powertools import Logger
>>> logger = Logger(service="payment")
>>>
>>> def handler(event, context):
logger.structure_logs(append=True, payment_id=event["payment_id"])
logger.info("Hello")
</code></pre>
<p><strong>Create child Logger using logging inheritance via child param</strong></p>
<pre><code>>>> # app.py
>>> import another_file
>>> from aws_lambda_powertools import Logger
>>> logger = Logger(service="payment")
>>>
>>> # another_file.py
>>> from aws_lambda_powertools import Logger
>>> logger = Logger(service="payment", child=True)
</code></pre>
<h2 id="raises">Raises</h2>
<dl>
<dt><code>InvalidLoggerSamplingRateError</code></dt>
<dd>When sampling rate provided is not a float</dd>
</dl>
<p>Initialize the logger with a name and an optional level.</p></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class Logger(logging.Logger): # lgtm [py/missing-call-to-init]
"""Creates and setups a logger to format statements in JSON.
Includes service name and any additional key=value into logs
It also accepts both service name or level explicitly via env vars
Environment variables
---------------------
POWERTOOLS_SERVICE_NAME : str
service name
LOG_LEVEL: str
logging level (e.g. INFO, DEBUG)
POWERTOOLS_LOGGER_SAMPLE_RATE: float
samping rate ranging from 0 to 1, 1 being 100% sampling
Parameters
----------
service : str, optional
service name to be appended in logs, by default "service_undefined"
level : str, int optional
logging.level, by default "INFO"
child: bool, optional
create a child Logger named <service>.<caller_file_name>, False by default
sample_rate: float, optional
sample rate for debug calls within execution context defaults to 0.0
stream: sys.stdout, optional
valid output for a logging stream, by default sys.stdout
Example
-------
**Setups structured logging in JSON for Lambda functions with explicit service name**
>>> from aws_lambda_powertools import Logger
>>> logger = Logger(service="payment")
>>>
>>> def handler(event, context):
logger.info("Hello")
**Setups structured logging in JSON for Lambda functions using env vars**
$ export POWERTOOLS_SERVICE_NAME="payment"
$ export POWERTOOLS_LOGGER_SAMPLE_RATE=0.01 # 1% debug sampling
>>> from aws_lambda_powertools import Logger
>>> logger = Logger()
>>>
>>> def handler(event, context):
logger.info("Hello")
**Append payment_id to previously setup logger**
>>> from aws_lambda_powertools import Logger
>>> logger = Logger(service="payment")
>>>
>>> def handler(event, context):
logger.structure_logs(append=True, payment_id=event["payment_id"])
logger.info("Hello")
**Create child Logger using logging inheritance via child param**
>>> # app.py
>>> import another_file
>>> from aws_lambda_powertools import Logger
>>> logger = Logger(service="payment")
>>>
>>> # another_file.py
>>> from aws_lambda_powertools import Logger
>>> logger = Logger(service="payment", child=True)
Raises
------
InvalidLoggerSamplingRateError
When sampling rate provided is not a float
"""
def __init__(
self,
service: str = None,
level: Union[str, int] = None,
child: bool = False,
sampling_rate: float = None,
stream: sys.stdout = None,
**kwargs,
):
self.service = resolve_env_var_choice(
choice=service, env=os.getenv(constants.SERVICE_NAME_ENV, "service_undefined")
)
self.sampling_rate = resolve_env_var_choice(
choice=sampling_rate, env=os.getenv(constants.LOGGER_LOG_SAMPLING_RATE, 0.0)
)
self._is_deduplication_disabled = resolve_truthy_env_var_choice(
env=os.getenv(constants.LOGGER_LOG_DEDUPLICATION_ENV, "false")
)
self.log_level = self._get_log_level(level)
self.child = child
self._handler = logging.StreamHandler(stream) if stream is not None else logging.StreamHandler(sys.stdout)
self._default_log_keys = {"service": self.service, "sampling_rate": self.sampling_rate}
self._logger = self._get_logger()
self._init_logger(**kwargs)
def __getattr__(self, name):
# Proxy attributes not found to actual logger to support backward compatibility
# https://github.com/awslabs/aws-lambda-powertools-python/issues/97
return getattr(self._logger, name)
def _get_logger(self):
""" Returns a Logger named {self.service}, or {self.service.filename} for child loggers"""
logger_name = self.service
if self.child:
logger_name = f"{self.service}.{self._get_caller_filename()}"
return logging.getLogger(logger_name)
def _init_logger(self, **kwargs):
"""Configures new logger"""
# Skip configuration if it's a child logger or a pre-configured logger
# to prevent the following:
# a) multiple handlers being attached
# b) different sampling mechanisms
# c) multiple messages from being logged as handlers can be duplicated
is_logger_preconfigured = getattr(self._logger, "init", False)
if self.child or is_logger_preconfigured:
return
self._configure_sampling()
self._logger.setLevel(self.log_level)
self._logger.addHandler(self._handler)
self.structure_logs(**kwargs)
# Pytest Live Log feature duplicates log records for colored output
# but we explicitly add a filter for log deduplication.
# This flag disables this protection when you explicit want logs to be duplicated (#262)
if not self._is_deduplication_disabled:
logger.debug("Adding filter in root logger to suppress child logger records to bubble up")
for handler in logging.root.handlers:
# It'll add a filter to suppress any child logger from self.service
# Example: `Logger(service="order")`, where service is Order
# It'll reject all loggers starting with `order` e.g. order.checkout, order.shared
handler.addFilter(SuppressFilter(self.service))
# as per bug in #249, we should not be pre-configuring an existing logger
# therefore we set a custom attribute in the Logger that will be returned
# std logging will return the same Logger with our attribute if name is reused
logger.debug(f"Marking logger {self.service} as preconfigured")
self._logger.init = True
def _configure_sampling(self):
"""Dynamically set log level based on sampling rate
Raises
------
InvalidLoggerSamplingRateError
When sampling rate provided is not a float
"""
try:
if self.sampling_rate and random.random() <= float(self.sampling_rate):
logger.debug("Setting log level to Debug due to sampling rate")
self.log_level = logging.DEBUG
except ValueError:
raise InvalidLoggerSamplingRateError(
f"Expected a float value ranging 0 to 1, but received {self.sampling_rate} instead."
f"Please review POWERTOOLS_LOGGER_SAMPLE_RATE environment variable."
)
def inject_lambda_context(self, lambda_handler: Callable[[Dict, Any], Any] = None, log_event: bool = None):
"""Decorator to capture Lambda contextual info and inject into logger
Parameters
----------
lambda_handler : Callable
Method to inject the lambda context
log_event : bool, optional
Instructs logger to log Lambda Event, by default False
Environment variables
---------------------
POWERTOOLS_LOGGER_LOG_EVENT : str
instruct logger to log Lambda Event (e.g. `"true", "True", "TRUE"`)
Example
-------
**Captures Lambda contextual runtime info (e.g memory, arn, req_id)**
from aws_lambda_powertools import Logger
logger = Logger(service="payment")
@logger.inject_lambda_context
def handler(event, context):
logger.info("Hello")
**Captures Lambda contextual runtime info and logs incoming request**
from aws_lambda_powertools import Logger
logger = Logger(service="payment")
@logger.inject_lambda_context(log_event=True)
def handler(event, context):
logger.info("Hello")
Returns
-------
decorate : Callable
Decorated lambda handler
"""
# If handler is None we've been called with parameters
# Return a partial function with args filled
if lambda_handler is None:
logger.debug("Decorator called with parameters")
return functools.partial(self.inject_lambda_context, log_event=log_event)
log_event = resolve_truthy_env_var_choice(
choice=log_event, env=os.getenv(constants.LOGGER_LOG_EVENT_ENV, "false")
)
@functools.wraps(lambda_handler)
def decorate(event, context):
lambda_context = build_lambda_context_model(context)
cold_start = _is_cold_start()
self.structure_logs(append=True, cold_start=cold_start, **lambda_context.__dict__)
if log_event:
logger.debug("Event received")
self.info(event)
return lambda_handler(event, context)
return decorate
def structure_logs(self, append: bool = False, **kwargs):
"""Sets logging formatting to JSON.
Optionally, it can append keyword arguments
to an existing logger so it is available
across future log statements.
Last keyword argument and value wins if duplicated.
Parameters
----------
append : bool, optional
[description], by default False
"""
# Child loggers don't have handlers attached, use its parent handlers
handlers = self._logger.parent.handlers if self.child else self._logger.handlers
for handler in handlers:
if append:
# Update existing formatter in an existing logger handler
handler.formatter.update_formatter(**kwargs)
else:
# Set a new formatter for a logger handler
handler.setFormatter(JsonFormatter(**self._default_log_keys, **kwargs))
@staticmethod
def _get_log_level(level: Union[str, int]) -> Union[str, int]:
""" Returns preferred log level set by the customer in upper case """
if isinstance(level, int):
return level
log_level: str = level or os.getenv("LOG_LEVEL")
if log_level is None:
return logging.INFO
return log_level.upper()
@staticmethod
def _get_caller_filename():
""" Return caller filename by finding the caller frame """
# Current frame => _get_logger()
# Previous frame => logger.py
# Before previous frame => Caller
frame = inspect.currentframe()
caller_frame = frame.f_back.f_back.f_back
return caller_frame.f_globals["__name__"]</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li>logging.Logger</li>
<li>logging.Filterer</li>
</ul>
<h3>Methods</h3>
<dl>
<dt id="aws_lambda_powertools.logging.Logger.inject_lambda_context"><code class="name flex">
<span>def <span class="ident">inject_lambda_context</span></span>(<span>self, lambda_handler=None, log_event=None)</span>
</code></dt>
<dd>
<section class="desc"><p>Decorator to capture Lambda contextual info and inject into logger</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>lambda_handler</code></strong> : <code>Callable</code></dt>
<dd>Method to inject the lambda context</dd>
<dt><strong><code>log_event</code></strong> : <code>bool</code>, optional</dt>
<dd>Instructs logger to log Lambda Event, by default False</dd>
</dl>
<h2 id="environment-variables">Environment variables</h2>
<dl>
<dt><strong><code>POWERTOOLS_LOGGER_LOG_EVENT</code></strong> : <code>str</code></dt>
<dd>instruct logger to log Lambda Event (e.g. <code>"true", "True", "TRUE"</code>)</dd>
</dl>
<h2 id="example">Example</h2>
<p><strong>Captures Lambda contextual runtime info (e.g memory, arn, req_id)</strong></p>
<pre><code>from aws_lambda_powertools import Logger
logger = Logger(service="payment")
@logger.inject_lambda_context
def handler(event, context):
logger.info("Hello")
</code></pre>
<p><strong>Captures Lambda contextual runtime info and logs incoming request</strong></p>
<pre><code>from aws_lambda_powertools import Logger
logger = Logger(service="payment")
@logger.inject_lambda_context(log_event=True)
def handler(event, context):
logger.info("Hello")
</code></pre>
<h2 id="returns">Returns</h2>
<dl>
<dt><strong><code>decorate</code></strong> : <code>Callable</code></dt>
<dd>Decorated lambda handler</dd>
</dl></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def inject_lambda_context(self, lambda_handler: Callable[[Dict, Any], Any] = None, log_event: bool = None):
"""Decorator to capture Lambda contextual info and inject into logger
Parameters
----------
lambda_handler : Callable
Method to inject the lambda context
log_event : bool, optional
Instructs logger to log Lambda Event, by default False
Environment variables
---------------------
POWERTOOLS_LOGGER_LOG_EVENT : str
instruct logger to log Lambda Event (e.g. `"true", "True", "TRUE"`)
Example
-------
**Captures Lambda contextual runtime info (e.g memory, arn, req_id)**
from aws_lambda_powertools import Logger
logger = Logger(service="payment")
@logger.inject_lambda_context
def handler(event, context):
logger.info("Hello")
**Captures Lambda contextual runtime info and logs incoming request**
from aws_lambda_powertools import Logger
logger = Logger(service="payment")
@logger.inject_lambda_context(log_event=True)
def handler(event, context):
logger.info("Hello")
Returns
-------
decorate : Callable
Decorated lambda handler
"""
# If handler is None we've been called with parameters
# Return a partial function with args filled
if lambda_handler is None:
logger.debug("Decorator called with parameters")
return functools.partial(self.inject_lambda_context, log_event=log_event)
log_event = resolve_truthy_env_var_choice(
choice=log_event, env=os.getenv(constants.LOGGER_LOG_EVENT_ENV, "false")
)
@functools.wraps(lambda_handler)
def decorate(event, context):
lambda_context = build_lambda_context_model(context)
cold_start = _is_cold_start()
self.structure_logs(append=True, cold_start=cold_start, **lambda_context.__dict__)
if log_event:
logger.debug("Event received")
self.info(event)
return lambda_handler(event, context)
return decorate</code></pre>
</details>
</dd>
<dt id="aws_lambda_powertools.logging.Logger.structure_logs"><code class="name flex">
<span>def <span class="ident">structure_logs</span></span>(<span>self, append=False, **kwargs)</span>
</code></dt>
<dd>
<section class="desc"><p>Sets logging formatting to JSON.</p>
<p>Optionally, it can append keyword arguments
to an existing logger so it is available
across future log statements.</p>
<p>Last keyword argument and value wins if duplicated.</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>append</code></strong> : <code>bool</code>, optional</dt>
<dd>[description], by default False</dd>
</dl></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def structure_logs(self, append: bool = False, **kwargs):
"""Sets logging formatting to JSON.
Optionally, it can append keyword arguments
to an existing logger so it is available
across future log statements.
Last keyword argument and value wins if duplicated.
Parameters
----------
append : bool, optional
[description], by default False
"""
# Child loggers don't have handlers attached, use its parent handlers
handlers = self._logger.parent.handlers if self.child else self._logger.handlers
for handler in handlers:
if append:
# Update existing formatter in an existing logger handler
handler.formatter.update_formatter(**kwargs)
else:
# Set a new formatter for a logger handler
handler.setFormatter(JsonFormatter(**self._default_log_keys, **kwargs))</code></pre>
</details>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="aws_lambda_powertools" href="../index.html">aws_lambda_powertools</a></code></li>
</ul>
</li>
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
<ul>
<li><code><a title="aws_lambda_powertools.logging.exceptions" href="exceptions.html">aws_lambda_powertools.logging.exceptions</a></code></li>
<li><code><a title="aws_lambda_powertools.logging.filters" href="filters.html">aws_lambda_powertools.logging.filters</a></code></li>
<li><code><a title="aws_lambda_powertools.logging.formatter" href="formatter.html">aws_lambda_powertools.logging.formatter</a></code></li>
<li><code><a title="aws_lambda_powertools.logging.lambda_context" href="lambda_context.html">aws_lambda_powertools.logging.lambda_context</a></code></li>
<li><code><a title="aws_lambda_powertools.logging.logger" href="logger.html">aws_lambda_powertools.logging.logger</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="aws_lambda_powertools.logging.Logger" href="#aws_lambda_powertools.logging.Logger">Logger</a></code></h4>
<ul class="">
<li><code><a title="aws_lambda_powertools.logging.Logger.inject_lambda_context" href="#aws_lambda_powertools.logging.Logger.inject_lambda_context">inject_lambda_context</a></code></li>
<li><code><a title="aws_lambda_powertools.logging.Logger.structure_logs" href="#aws_lambda_powertools.logging.Logger.structure_logs">structure_logs</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.7.5</a>.</p>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad()</script>
</body>
</html>