-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogging-python.html
556 lines (479 loc) · 34 KB
/
logging-python.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>Logging in python</title>
<meta content="" name="description">
<meta content="" name="keywords">
<!-- Favicons -->
<link href="assets/img/Favicon-1.png" rel="icon">
<link href="assets/img/Favicon-1.png" rel="apple-touch-icon">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
<!-- Vendor CSS Files -->
<link href="assets/vendor/aos/aos.css" rel="stylesheet">
<link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
<link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
<link href="assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet">
<link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet">
<!-- Creating a python code section-->
<link rel="stylesheet" href="assets/css/prism.css">
<script src="assets/js/prism.js"></script>
<!-- Template Main CSS File -->
<link href="assets/css/style.css" rel="stylesheet">
<!-- To set the icon, visit https://fontawesome.com/account-->
<script src="https://kit.fontawesome.com/5d25c1efd3.js" crossorigin="anonymous"></script>
<!-- end of icon-->
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML">
</script>
<!-- =======================================================
* Template Name: iPortfolio
* Updated: Sep 18 2023 with Bootstrap v5.3.2
* Template URL: https://bootstrapmade.com/iportfolio-bootstrap-portfolio-websites-template/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
======================================================== -->
</head>
<body>
<!-- ======= Mobile nav toggle button ======= -->
<i class="bi bi-list mobile-nav-toggle d-xl-none"></i>
<!-- ======= Header ======= -->
<header id="header">
<div class="d-flex flex-column">
<div class="profile">
<img src="assets/img/myphoto.jpeg" alt="" class="img-fluid rounded-circle">
<h1 class="text-light"><a href="index.html">Arun</a></h1>
<div class="social-links mt-3 text-center">
<a href="https://www.linkedin.com/in/arunp77/" target="_blank" class="linkedin"><i class="bx bxl-linkedin"></i></a>
<a href="https://github.com/arunp77" target="_blank" class="github"><i class="bx bxl-github"></i></a>
<a href="https://twitter.com/arunp77_" target="_blank" class="twitter"><i class="bx bxl-twitter"></i></a>
<a href="https://www.instagram.com/arunp77/" target="_blank" class="instagram"><i class="bx bxl-instagram"></i></a>
<a href="https://arunp77.medium.com/" target="_blank" class="medium"><i class="bx bxl-medium"></i></a>
</div>
</div>
<nav id="navbar" class="nav-menu navbar">
<ul>
<li><a href="index.html#hero" class="nav-link scrollto active"><i class="bx bx-home"></i> <span>Home</span></a></li>
<li><a href="index.html#about" class="nav-link scrollto"><i class="bx bx-user"></i> <span>About</span></a></li>
<li><a href="index.html#resume" class="nav-link scrollto"><i class="bx bx-file-blank"></i> <span>Resume</span></a></li>
<li><a href="index.html#portfolio" class="nav-link scrollto"><i class="bx bx-book-content"></i> <span>Portfolio</span></a></li>
<li><a href="index.html#skills-and-tools" class="nav-link scrollto"><i class="bx bx-wrench"></i> <span>Skills and Tools</span></a></li>
<li><a href="index.html#language" class="nav-link scrollto"><i class="bi bi-menu-up"></i> <span>Languages</span></a></li>
<li><a href="index.html#awards" class="nav-link scrollto"><i class="bi bi-award-fill"></i> <span>Awards</span></a></li>
<li><a href="index.html#professionalcourses" class="nav-link scrollto"><i class="bx bx-book-alt"></i> <span>Professional Certification</span></a></li>
<li><a href="index.html#publications" class="nav-link scrollto"><i class="bx bx-news"></i> <span>Publications</span></a></li>
<li><a href="index.html#extra-curricular" class="nav-link scrollto"><i class="bx bx-rocket"></i> <span>Extra-Curricular Activities</span></a></li>
<!-- <li><a href="#contact" class="nav-link scrollto"><i class="bx bx-envelope"></i> <span>Contact</span></a></li> -->
</ul>
</nav><!-- .nav-menu -->
</div>
</header><!-- End Header -->
<main id="main">
<!-- ======= Breadcrumbs ======= -->
<section id="breadcrumbs" class="breadcrumbs">
<div class="container">
<div class="d-flex justify-content-between align-items-center">
<h2>Python</h2>
<ol>
<li><a href="portfolio-details.html" class="clickable-box">Content section</a></li>
<li><a href="index.html#portfolio" class="clickable-box">Portfolio section</a></li>
</ol>
</div>
</div>
</section><!-- End Breadcrumbs -->
<!------ right dropdown menue ------->
<div class="right-side-list">
<div class="dropdown">
<button class="dropbtn"><strong>Shortcuts:</strong></button>
<div class="dropdown-content">
<ul>
<li><a href="cloud-compute.html"><i class="fas fa-cloud"></i> Cloud</a></li>
<li><a href="AWS-GCP.html"><i class="fas fa-cloud"></i> AWS-GCP</a></li>
<li><a href="amazon-s3.html"><i class="fas fa-cloud"></i> AWS S3</a></li>
<li><a href="ec2-confi.html"><i class="fas fa-server"></i> EC2</a></li>
<li><a href="Docker-Container.html"><i class="fab fa-docker" style="color: rgb(29, 27, 27);"></i> Docker</a></li>
<li><a href="Jupyter-nifi.html"><i class="fab fa-python" style="color: rgb(34, 32, 32);"></i> Jupyter-nifi</a></li>
<li><a href="snowflake-task-stream.html"><i class="fas fa-snowflake"></i> Snowflake</a></li>
<li><a href="data-model.html"><i class="fas fa-database"></i> Data modeling</a></li>
<li><a href="sql-basics.html"><i class="fas fa-table"></i> QL</a></li>
<li><a href="sql-basic-details.html"><i class="fas fa-database"></i> SQL</a></li>
<li><a href="Bigquerry-sql.html"><i class="fas fa-database"></i> Bigquery</a></li>
<li><a href="scd.html"><i class="fas fa-archive"></i> SCD</a></li>
<li><a href="sql-project.html"><i class="fas fa-database"></i> SQL project</a></li>
<!-- Add more subsections as needed -->
</ul>
</div>
</div>
</div>
<!-- ======= Portfolio Details Section ======= -->
<section id="portfolio-details" class="portfolio-details">
<div class="container">
<div class="row gy-4">
<h1>Logging in Python</h1>
<div class="col-lg-8">
<div class="portfolio-details-slider swiper">
<div class="swiper-wrapper align-items-center">
<figure>
<img src="assets/img/machine-ln/in-depth-python-logging.png" alt="" style="max-width: 100%; max-height: auto;">
<figcaption style="text-align: center;"></figcaption>
</figure>
</div>
<div class="swiper-pagination"></div>
</div>
</div>
<div class="col-lg-4 grey-box">
<div class="section-title">
<h3>Table of Contents</h3>
<ol>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#project">Project: To-Do List Application</a></li>
<li><a href="#reference">Reference</a></li>
</ol>
</div>
</div>
</div>
<section>
<h2 id="introduction">Introduction</h2>
Logging is an essential aspect of software development that helps track events that happen when software runs. Python's <code>logging</code> module provides a flexible framework for emitting log messages from Python programs. By using logging, you can gain insights into your application's behavior, diagnose problems, and audit operations.
<ol>
<li><b>Why Use Logging?</b>
<ul>
<li><b>Debugging:</b> Logs help track down bugs by providing detailed information about program execution.</li>
<li><b>Monitoring:</b> Logs can be used to monitor application behavior over time.</li>
<li><b>Auditing:</b> Logs provide a record of activities, which is essential for auditing and compliance.</li>
<li><b>Error Reporting:</b> Logs capture errors and exceptions, which helps in understanding failures and fixing them.</li>
</ul>
</li>
<li><b>Basics of Python Logging: </b>
<ul>
<li><b>mporting the Logging Module: </b>To start using logging, you need to import Python's built-in <code>logging</code> module: <code>import logging</code></li>
<li><b>Basic Logging Configuration: </b>The simplest way to log messages is by configuring the logging system with basic settings using <code>logging.basicConfig()</code>.
<pre class="language-python"><code>
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")
</code></pre>
we will get following, if we run the script:
<pre><code>
DEBUG:root:This is a debug message
INFO:root:This is an info message
WARNING:root:This is a warning message
ERROR:root:This is an error message
CRITICAL:root:This is a critical message
</code></pre>
</li>
<li><b>Logging Levels: </b>Logging levels determine the severity of the events being logged. The standard levels, in increasing order of severity, are:
<ul>
<li><code>DEBUG</code>: Detailed information, typically of interest only when diagnosing problems.</li>
<li><code>INFO</code>: Confirmation that things are working as expected.</li>
<li><code>WARNING</code>: An indication that something unexpected happened, or indicative of some problem in the near future (e.g., ‘disk space low’). The software is still working as expected.</li>
<li><code>ERROR</code>: Due to a more serious problem, the software has not been able to perform some function.</li>
<li><code>CRITICAL</code>: A very serious error, indicating that the program itself may be unable to continue running.</li>
</ul>
By default, the logging module logs messages with a severity level of <code>WARNING</code> or above unless configured otherwise.
<p><b>Basic Example: </b></p>
<pre class="language-python"><code>
import logging
logging.basicConfig(level=logging.INFO)
def divide(a, b):
logging.info(f"Dividing {a} by {b}")
try:
result = a / b
except ZeroDivisionError:
logging.error("Attempted to divide by zero")
return None
else:
return result
result = divide(10, 0) # This will trigger an error log
</code></pre>
<pre>
INFO:root:Dividing 10 by 0
ERROR:root:Attempted to divide by zero
</pre>
</p>
</li>
<li><b>Advanced Logging Configuration: </b>
<ul>
<li><b>Configuring Log Output Format: </b>You can customize the log message format using the <code>format</code> argument in <code>basicConfig()</code>.
<pre class="language-python"><code>
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.info("This is an info message with a custom format")
</code></pre>
<pre>
INFO:root:This is an info message with a custom format
</pre>
</li>
<li><b>Logging to a File: </b>You can configure logging to output messages to a file instead of the console.
<pre class="language-python"><code>
import logging
logging.basicConfig(
filename='app.log',
filemode='w',
level=logging.DEBUG,
format='%(name)s - %(levelname)s - %(message)s'
)
logging.debug("This message will be logged to a file")
logging.info("This is another message logged to the file")
</code></pre>
</li>
<li><b>Adding Multiple Handlers: </b>Handlers are responsible for sending the log messages to the specified destination, such as the console, files, or external systems. You can configure multiple handlers to direct logs to multiple destinations.
<pre class="language-python"><code>
import logging
# Create a logger
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
# Create console handler and set level to debug
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
# Create file handler and set level to warning
file_handler = logging.FileHandler('my_app.log')
file_handler.setLevel(logging.WARNING)
# Create a formatter and set it for both handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
# Add handlers to the logger
logger.addHandler(console_handler)
logger.addHandler(file_handler)
# Example log messages
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")
</code></pre>
where:
<ul>
<li>The console handler will log messages of all levels to the console.</li>
<li>The file handler will log messages of level <code>WARNING</code> and above to the file <code>my_app.log</code>.</li>
</ul>
<li><b>Loggers, Handlers, and Formatters: </b>
<ul>
<li><b>Logger:</b> The entry point for the logging system. Each logger can have multiple handlers.</li>
<li><b>Handler:</b> Directs the log messages to the appropriate destination (e.g., console, file).</li>
<li><b>Formatter:</b> Defines the format of the log messages.</li>
</ul>
<pre class="language-python"><code>
import logging
# Logger configuration
logger = logging.getLogger('example_logger')
logger.setLevel(logging.DEBUG)
# Handler configuration
handler = logging.FileHandler('example.log')
handler.setLevel(logging.DEBUG)
# Formatter configuration
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# Add the handler to the logger
logger.addHandler(handler)
# Example usage
logger.info("This is an info message")
</code></pre>
</li>
<li><b>Rotating Log Files: </b>For long-running applications, log files can become very large. Python’s <code>logging.handlers</code> module provides a <code>RotatingFileHandler</code> that can rotate log files based on size or time.
<pre class="language-python"><code>
import logging
from logging.handlers import RotatingFileHandler
handler = RotatingFileHandler('app.log', maxBytes=2000, backupCount=5)
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
# Example log messages to generate file rotation
for i in range(100):
logger.debug(f"This is log message {i}")
</code></pre>
where:
<ul>
<li><code>maxBytes=2000</code>: The log file will rotate when it reaches 2000 bytes.</li>
<li><code>backupCount=5</code>: Keeps the last 5 log files as backups.</li>
</ul>
</li>
</li>
</ul>
</li>
<li><b>Logging Best Practices: </b>
<ul>
<li><b>Use the Appropriate Logging Level:</b> Choose the appropriate logging level (<code>DEBUG</code>, <code>INFO</code>, <code>WARNING</code>, <code>ERROR</code>, <code>CRITICAL</code>) based on the importance of the message.</li>
<li><b>Avoid Using Print Statements for Logging:</b> Use the logging module instead of print statements for better control and flexibility.</li>
<li><b>Configure Logging Early in the Program:</b> Set up logging configurations at the start of your program to ensure consistent logging throughout.</li>
<li><b>Use Logging for Exception Handling:</b> Log exceptions to capture stack traces and error details for debugging.</li>
</ul>
<p><b>Example: Logging in Exception Handling</b></p>
<pre class="language-python"><code>
import logging
logging.basicConfig(level=logging.ERROR)
try:
result = 10 / 0
except ZeroDivisionError as e:
logging.error("Exception occurred", exc_info=True)
</code></pre>
This will log the exception details, including the stack trace, which is useful for debugging.
</li>
</ul>
</li>
</ol>
Logging is a crucial part of developing reliable, maintainable, and scalable software. Python’s logging module provides a robust and flexible framework for handling logging in applications. By understanding and utilizing logging, you can track your application's behavior, troubleshoot issues, and ensure smoother operation in production environments.
<!-------------------------------------------------->
<h3 id="project">Project: To-Do List Application</h3>
<p><b>Objective: </b>Build a simple command-line To-Do List application with logging to track user actions and application errors.</p>
<p><strong>For more details, please checkout the </strong><a href="https://github.com/arunp77/Data-engineering-tools/tree/main/Python-loogin-todo-list" target="_blank">github repository</a>.</p>
<p><b>Project Structure:</b> </p>
<pre><code>
# Readme.md
todo_app/
│
├── todo.py # Main application file
├── logger.py # Logging configuration file
└── todo.log # Log file (generated after running the application)
</code></pre>
<ul>
<li><strong><code>logger.py</code>: Setting Up Logging: </strong> Create a logger.py file to configure the logging for the project.
<pre class="language-python"><code>
# logger.py
import logging
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("todo.log"),
logging.StreamHandler()
]
)
# Create a logger object
logger = logging.getLogger('todo_app')
</code></pre>
</li>
<li><strong><code>todo.py</code>: Main Application Logic</strong>
<pre class="language-python"><code>
# todo.py
from logger import logger
class ToDoApp:
def __init__(self):
self.tasks = []
logger.info("To-Do application started")
def add_task(self, task):
if task:
self.tasks.append(task)
logger.info(f"Task added: {task}")
else:
logger.warning("Empty task cannot be added")
def complete_task(self, task_index):
try:
completed_task = self.tasks.pop(task_index)
logger.info(f"Task completed: {completed_task}")
except IndexError:
logger.error(f"Task index {task_index} is out of range")
def show_tasks(self):
if not self.tasks:
logger.info("No tasks to show")
print("No tasks in the to-do list.")
else:
print("To-Do List:")
for idx, task in enumerate(self.tasks):
print(f"{idx + 1}. {task}")
logger.info(f"{len(self.tasks)} tasks shown")
def main():
app = ToDoApp()
while True:
print("\nOptions:")
print("1. Add Task")
print("2. Complete Task")
print("3. Show Tasks")
print("4. Exit")
choice = input("Choose an option: ")
if choice == '1':
task = input("Enter the task: ")
app.add_task(task)
elif choice == '2':
task_index = int(input("Enter the task number to complete: ")) - 1
app.complete_task(task_index)
elif choice == '3':
app.show_tasks()
elif choice == '4':
logger.info("Exiting the To-Do application")
print("Goodbye!")
break
else:
logger.warning(f"Invalid option selected: {choice}")
print("Invalid option, please try again.")
if __name__ == "__main__":
main()
</code></pre>
</li>
</ul>
<figure>
<img src="assets/img/data-engineering/todolist1.png" alt="" style="max-width: 100%; max-height: auto;">
<figcaption style="text-align: center;"></figcaption>
</figure>
<p>The log file <code>todo.log</code> looks like this now:</p>
<figure>
<img src="assets/img/data-engineering/todolist2.png" alt="" style="max-width: 100%; max-height: auto;">
<figcaption style="text-align: center;"></figcaption>
</figure>
</section>
<!-------Reference ------->
<section id="reference">
<h3>References</h3>
<ol>
<li>Udemy playlist on advanced python by Krish Naik</li>
<li>For more details, please chekout the <a href="https://docs.python.org/3/library/logging.html" target="_blank">official documentation</a>.</li>
</ol>
</section>
<hr>
<div style="background-color: #f0f0f0; padding: 15px; border-radius: 5px;">
<h3>Some other interesting things to know:</h3>
<ul style="list-style-type: disc; margin-left: 30px;">
<li>Visit my website on <a href="sql-project.html">For Data, Big Data, Data-modeling, Datawarehouse, SQL, cloud-compute.</a></li>
<li>Visit my website on <a href="Data-engineering.html">Data engineering</a></li>
</ul>
</div>
<p></p>
<div class="navigation">
<a href="index.html#portfolio" class="clickable-box">
<span class="arrow-left">Portfolio section</span>
</a>
<a href="portfolio-details.html" class="clickable-box">
<span class="arrow-right">Content</span>
</a>
</div>
</div>
</section><!-- End Portfolio Details Section -->
</main><!-- End #main --
<!-- ======= Footer ======= -->
<footer id="footer">
<div class="container">
<div class="copyright">
© Copyright <strong><span>Arun</span></strong>
</div>
</div>
</footer><!-- End Footer -->
<a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>
<!-- Vendor JS Files -->
<script src="assets/vendor/purecounter/purecounter_vanilla.js"></script>
<script src="assets/vendor/aos/aos.js"></script>
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/glightbox/js/glightbox.min.js"></script>
<script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="assets/vendor/swiper/swiper-bundle.min.js"></script>
<script src="assets/vendor/typed.js/typed.umd.js"></script>
<script src="assets/vendor/waypoints/noframework.waypoints.js"></script>
<script src="assets/vendor/php-email-form/validate.js"></script>
<!-- Template Main JS File -->
<script src="assets/js/main.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
hljs.initHighlightingOnLoad();
});
</script>
</body>
</html>