Gỡ lỗi nhật ký Python là gì?

Khi bạn chạy tập lệnh python, bạn muốn biết phần nào của tập lệnh đang được thực thi và kiểm tra giá trị mà các biến giữ

Thông thường, bạn có thể chỉ cần '_______0_______1' đưa ra các thông báo có ý nghĩa để bạn có thể nhìn thấy chúng trong bảng điều khiển. Và đây có lẽ là tất cả những gì bạn cần khi phát triển các chương trình nhỏ.

Vấn đề là, khi bạn sử dụng phương pháp này cho các dự án lớn hơn với nhiều mô-đun, bạn muốn có một cách tiếp cận linh hoạt hơn

Tại sao?

Bởi vì, mã có thể trải qua các giai đoạn khác nhau như trong quá trình phát triển, gỡ lỗi, xem xét, thử nghiệm hoặc trong sản xuất

Loại tin nhắn bạn muốn in ra trong quá trình phát triển có thể rất khác với loại tin nhắn bạn muốn xem khi nó được đưa vào sản xuất. Tùy theo mục đích muốn code in ra các loại thông báo khác nhau

Điều này có thể trở nên rườm rà với các câu lệnh

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
2 và
import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
3. Bên cạnh đó, bạn muốn có một hệ thống phân cấp nhất định khi in thư.

Ý tôi là, trong một lần chạy 'thử nghiệm' nhất định, bạn chỉ muốn xem các cảnh báo và thông báo lỗi. Trong khi trong quá trình 'gỡ lỗi', bạn không chỉ muốn xem các cảnh báo và thông báo lỗi mà còn cả các thông báo liên quan đến gỡ lỗi. Hãy tưởng tượng làm điều này với các câu lệnh '

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
2' trong một dự án đa mô-đun

Nếu bạn muốn in mô-đun nào và mã được chạy vào thời điểm nào, mã của bạn có thể dễ dàng trở nên lộn xộn hơn

Có một tin tốt. Tất cả những vấn đề này được giải quyết độc đáo bởi mô-đun

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
5

Sử dụng ghi nhật ký, bạn có thể

  1. Kiểm soát cấp độ thông báo để chỉ đăng nhập những thông báo cần thiết
  2. Kiểm soát nơi hiển thị hoặc lưu nhật ký
  3. Kiểm soát cách định dạng nhật ký bằng các mẫu tin nhắn tích hợp
  4. Biết thông báo đến từ mô-đun nào

Bạn có thể nói 'Tôi thấy rằng

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
5 có thể hữu ích nhưng nó có vẻ quá kỹ thuật và có vẻ hơi khó nắm bắt'. Vâng, vâng,
import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
5 yêu cầu một chút đường cong học tập nhưng đó là mục đích của bài đăng này. làm cho đăng nhập dễ học

Không chậm trễ nữa, hãy bắt tay ngay vào nó

Chương trình nhà khoa học dữ liệu công nghiệp MLPlus

Bạn có muốn học Khoa học dữ liệu từ các Nhà khoa học dữ liệu có kinh nghiệm không?

Xây dựng sự nghiệp khoa học dữ liệu của bạn với bằng cấp được ngành công nhận trên toàn cầu. Giải quyết các dự án với dữ liệu thực của công ty và trở thành Nhà khoa học dữ liệu được chứng nhận trong vòng chưa đầy 12 tháng.

Nhận khóa học Python hoàn chỉnh miễn phí

Xây dựng sự nghiệp khoa học dữ liệu của bạn với bằng cấp được ngành công nhận trên toàn cầu. Có được tư duy, sự tự tin và các kỹ năng khiến Nhà khoa học dữ liệu trở nên có giá trị

2. Một ví dụ ghi nhật ký cơ bản

Python cung cấp một mô-đun

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
5 dựng sẵn, là một phần của thư viện chuẩn python. Vì vậy, bạn không cần phải cài đặt bất cứ điều gì

Để sử dụng ghi nhật ký, tất cả những gì bạn cần làm là thiết lập cấu hình cơ bản bằng cách sử dụng

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
9. Trên thực tế, đây cũng là tùy chọn. Chúng ta sẽ thấy về điều đó sớm

Sau đó, thay vì

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
1, bạn gọi
import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
1 để hiển thị thông báo trong bảng điều khiển

import logging
logging.basicConfig[level=logging.INFO]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

logging.info["Hypotenuse of {a}, {b} is {c}".format[a=3, b=4, c=hypotenuse[a,b]]]
#> INFO:root:Hypotenuse of 3, 4 is 5.0

Thông báo nhật ký được in có định dạng mặc định sau. {MỨC ĐỘ}. {TIỀU PHU}. {THÔNG ĐIỆP}

Trong trường hợp trên, mức độ là

import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
2, bởi vì, tôi đã gọi là
import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
3

Trình ghi nhật ký có tên là

import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
4, vì đó là trình ghi mặc định và tôi chưa tạo một trình ghi mới

Nhưng một logger dù sao là gì?

Trình ghi nhật ký giống như một thực thể mà bạn có thể tạo và định cấu hình để ghi lại các loại và định dạng thư khác nhau

Bạn có thể định cấu hình một trình ghi nhật ký in ra bàn điều khiển và một trình ghi nhật ký khác gửi nhật ký tới một tệp, có cấp độ ghi nhật ký khác và dành riêng cho một mô-đun nhất định. Nhiều giải thích và ví dụ sắp tới về điều này

Cuối cùng, tin nhắn là chuỗi tôi đã chuyển đến

import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
3

Bây giờ, điều gì sẽ xảy ra nếu bạn không thiết lập

import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
6?

Trả lời. Nhật ký sẽ không được in

Tại sao?

Để biết điều đó, hãy hiểu các cấp độ ghi nhật ký

3. 5 cấp độ đăng nhập

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
5 có 5 cấp nhật ký phân cấp khác nhau mà một trình ghi cụ thể có thể được định cấu hình để

Hãy xem tài liệu python nói gì về từng cấp độ

  1. GỠ LỖI. Thông tin chi tiết, để chẩn đoán vấn đề. Giá trị=10
  2. THÔNG TIN. Xác nhận mọi thứ đang hoạt động như mong đợi. Giá trị=20
  3. CẢNH BÁO. Một cái gì đó bất ngờ đã xảy ra, hoặc dấu hiệu của một số vấn đề. Nhưng phần mềm vẫn hoạt động như mong đợi. Giá trị=30
  4. LỖI. Vấn đề nghiêm trọng hơn, phần mềm không thể thực hiện một số chức năng. Giá trị=40
  5. BẠO KÍCH. Một lỗi nghiêm trọng, chương trình có thể không thể tiếp tục chạy. Giá trị=50

Bây giờ, quay lại câu hỏi trước đó về điều gì sẽ xảy ra nếu bạn không thiết lập

import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
6 trong ví dụ trước

Câu trả lời là. nhật ký sẽ không được in vì, trình ghi nhật ký mặc định là 'root' và mức cấu hình cơ bản mặc định của nó là 'CẢNH BÁO'. Điều đó có nghĩa là, chỉ những tin nhắn từ

import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
9 trở lên mới được ghi lại

Vì vậy, thông báo của

import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
3 sẽ không được in. Và đó là lý do tại sao cấu hình cơ bản ban đầu được đặt là
import logging
logging.basicConfig[level=logging.INFO, format='%[asctime]s :: %[levelname]s :: %[message]s']
logging.info["Just like that!"]
#> 2019-02-17 11:40:38,254 :: INFO :: Just like that!
1 [trong
import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
6]

Thay vào đó, nếu tôi đặt mức là

import logging
logging.basicConfig[level=logging.INFO, format='%[asctime]s :: %[levelname]s :: %[message]s']
logging.info["Just like that!"]
#> 2019-02-17 11:40:38,254 :: INFO :: Just like that!
3, thì chỉ tin nhắn từ
import logging
logging.basicConfig[level=logging.INFO, format='%[asctime]s :: %[levelname]s :: %[message]s']
logging.info["Just like that!"]
#> 2019-02-17 11:40:38,254 :: INFO :: Just like that!
4 và
import logging
logging.basicConfig[level=logging.INFO, format='%[asctime]s :: %[levelname]s :: %[message]s']
logging.info["Just like that!"]
#> 2019-02-17 11:40:38,254 :: INFO :: Just like that!
5 sẽ được ghi lại. Thông thoáng?

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0

4. Cách đăng nhập vào một tệp thay vì bảng điều khiển

Để gửi thông báo tường trình tới một tệp từ trình ghi nhật ký gốc, bạn cần đặt đối số tệp trong

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
9

import logging
logging.basicConfig[level=logging.INFO, file='sample.log']

Giờ đây, tất cả các thông báo nhật ký tiếp theo sẽ chuyển thẳng đến tệp 'mẫu. log' trong thư mục làm việc hiện tại của bạn. Nếu bạn muốn gửi nó tới một tệp trong một thư mục khác, hãy cung cấp đường dẫn tệp đầy đủ

5. Cách thay đổi định dạng nhật ký

Mô-đun ghi nhật ký cung cấp các tốc ký để thêm các chi tiết khác nhau vào các thông báo đã ghi. Hình ảnh dưới đây từ tài liệu Python hiển thị danh sách đó

Định dạng ghi nhật ký

Hãy thay đổi định dạng thông báo nhật ký để hiển thị THỜI GIAN, CẤP ĐỘ và TIN NHẮN. Để làm điều đó, chỉ cần thêm định dạng vào đối số định dạng của

import logging
logging.basicConfig[level=logging.INFO, format='%[asctime]s :: %[levelname]s :: %[message]s']
logging.info["Just like that!"]
#> 2019-02-17 11:40:38,254 :: INFO :: Just like that!
7

import logging
logging.basicConfig[level=logging.INFO, format='%[asctime]s :: %[levelname]s :: %[message]s']
logging.info["Just like that!"]
#> 2019-02-17 11:40:38,254 :: INFO :: Just like that!

6. Tại sao làm việc với bộ ghi gốc cho tất cả các mô-đun không phải là ý tưởng tốt nhất

Bởi vì tất cả chúng sẽ chia sẻ cùng một bộ ghi 'gốc'

Nhưng tại sao điều đó lại tồi tệ?

Hãy xem đoạn mã dưới đây

# 1. code inside myprojectmodule.py
import logging
logging.basicConfig[file='module.log']

#-----------------------------

# 2. code inside main.py [imports the code from myprojectmodule.py]
import logging
import myprojectmodule  # This runs the code in myprojectmodule.py

logging.basicConfig[file='main.log']  # No effect, because!

Hãy tưởng tượng bạn có một hoặc nhiều mô-đun trong dự án của mình. Và các mô-đun này sử dụng mô-đun gốc cơ bản. Sau đó, khi nhập mô-đun [‘______21_______8‘], tất cả mã của mô-đun đó sẽ chạy và bộ ghi được cấu hình

Sau khi được định cấu hình, bộ ghi gốc trong tệp chính [đã nhập mô-đun '

import logging
logging.basicConfig[level=logging.INFO, format='%[asctime]s :: %[levelname]s :: %[message]s']
logging.info["Just like that!"]
#> 2019-02-17 11:40:38,254 :: INFO :: Just like that!
9'] sẽ không thể thay đổi cài đặt bộ ghi gốc nữa. Bởi vì, không thể thay đổi bộ
import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
9 một lần

Điều đó có nghĩa là, nếu bạn muốn ghi nhật ký các thông báo từ

import logging
logging.basicConfig[level=logging.INFO, format='%[asctime]s :: %[levelname]s :: %[message]s']
logging.info["Just like that!"]
#> 2019-02-17 11:40:38,254 :: INFO :: Just like that!
9 vào một tệp và nhật ký từ mô-đun chính vào một tệp khác, trình ghi nhật ký gốc không thể làm điều đó

Để làm điều đó, bạn cần tạo một logger mới

7. Làm thế nào để tạo một logger mới?

Bạn có thể tạo một nhật ký mới bằng cách sử dụng phương thức ‘______31_______2‘. Nếu tồn tại một bộ ghi có cùng tên, thì bộ ghi đó sẽ được sử dụng

Mặc dù bạn có thể đặt bất kỳ tên nào cho bộ ghi nhật ký, quy ước là sử dụng biến

# 1. code inside myprojectmodule.py
import logging
logging.basicConfig[file='module.log']

#-----------------------------

# 2. code inside main.py [imports the code from myprojectmodule.py]
import logging
import myprojectmodule  # This runs the code in myprojectmodule.py

logging.basicConfig[file='main.log']  # No effect, because!
3 như thế này

logger = logging.getLogger[__name__]
logger.info['my logging message']

Nhưng, tại sao lại sử dụng

# 1. code inside myprojectmodule.py
import logging
logging.basicConfig[file='module.log']

#-----------------------------

# 2. code inside main.py [imports the code from myprojectmodule.py]
import logging
import myprojectmodule  # This runs the code in myprojectmodule.py

logging.basicConfig[file='main.log']  # No effect, because!
3 làm tên của thiết bị ghi nhật ký, thay vì mã hóa cứng một tên?

Bởi vì biến

# 1. code inside myprojectmodule.py
import logging
logging.basicConfig[file='module.log']

#-----------------------------

# 2. code inside main.py [imports the code from myprojectmodule.py]
import logging
import myprojectmodule  # This runs the code in myprojectmodule.py

logging.basicConfig[file='main.log']  # No effect, because!
3 sẽ giữ tên của mô-đun [tệp python] đã gọi mã. Vì vậy, khi được sử dụng bên trong một mô-đun, nó sẽ tạo một bộ ghi nhật ký mang giá trị được cung cấp bởi thuộc tính
# 1. code inside myprojectmodule.py
import logging
logging.basicConfig[file='module.log']

#-----------------------------

# 2. code inside main.py [imports the code from myprojectmodule.py]
import logging
import myprojectmodule  # This runs the code in myprojectmodule.py

logging.basicConfig[file='main.log']  # No effect, because!
3 của mô-đun

Bằng cách này, nếu bạn thay đổi tên mô-đun [tên tệp] trong tương lai, bạn không phải sửa đổi mã nội bộ

Bây giờ, khi bạn đã tạo một trình ghi nhật ký mới, bạn nên nhớ ghi nhật ký tất cả các thư của mình bằng cách sử dụng phương thức

# 1. code inside myprojectmodule.py
import logging
logging.basicConfig[file='module.log']

#-----------------------------

# 2. code inside main.py [imports the code from myprojectmodule.py]
import logging
import myprojectmodule  # This runs the code in myprojectmodule.py

logging.basicConfig[file='main.log']  # No effect, because!
7 mới thay vì phương thức
import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
3 của thư mục gốc

Một khía cạnh khác cần lưu ý là, tất cả các trình ghi nhật ký đều có hệ thống phân cấp tích hợp sẵn.

Ý tôi là gì?

Ví dụ: nếu bạn đã định cấu hình trình ghi nhật ký gốc để ghi các thông báo vào một tệp cụ thể. Bạn cũng có một trình ghi nhật ký tùy chỉnh mà bạn chưa định cấu hình trình xử lý tệp để gửi tin nhắn tới bảng điều khiển hoặc tệp nhật ký khác

Trong trường hợp này, bộ ghi tùy chỉnh sẽ dự phòng và ghi vào tệp do chính bộ ghi gốc thiết lập. Cho đến khi và trừ khi bạn định cấu hình tệp nhật ký của trình ghi nhật ký tùy chỉnh của mình

Vậy trình xử lý tệp là gì và cách thiết lập?

8. Trình xử lý và định dạng tệp là gì và làm cách nào để thiết lập?

Các lớp

# 1. code inside myprojectmodule.py
import logging
logging.basicConfig[file='module.log']

#-----------------------------

# 2. code inside main.py [imports the code from myprojectmodule.py]
import logging
import myprojectmodule  # This runs the code in myprojectmodule.py

logging.basicConfig[file='main.log']  # No effect, because!
9 và
logger = logging.getLogger[__name__]
logger.info['my logging message']
0 được sử dụng để thiết lập tệp đầu ra và định dạng của thông báo cho các trình ghi nhật ký khác với trình ghi nhật ký gốc

Bạn có nhớ cách chúng tôi thiết lập tên tệp và định dạng của thông báo trong bộ ghi gốc [bên trong

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
9] trước đó không?

Chúng tôi vừa chỉ định các tham số

logger = logging.getLogger[__name__]
logger.info['my logging message']
2 và
logger = logging.getLogger[__name__]
logger.info['my logging message']
3 trong
import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
9 và tất cả các bản ghi tiếp theo đều chuyển đến tệp đó

Tuy nhiên, khi bạn tạo một bộ ghi riêng, bạn cần thiết lập chúng riêng lẻ bằng cách sử dụng các đối tượng

logger = logging.getLogger[__name__]
logger.info['my logging message']
5 và
logger = logging.getLogger[__name__]
logger.info['my logging message']
6

Một

logger = logging.getLogger[__name__]
logger.info['my logging message']
7 được sử dụng để làm cho trình ghi nhật ký tùy chỉnh của bạn đăng nhập vào một tệp khác. Tương tự như vậy, một
logger = logging.getLogger[__name__]
logger.info['my logging message']
8 được sử dụng để thay đổi định dạng của các tin nhắn đã ghi của bạn

import logging

# Gets or creates a logger
logger = logging.getLogger[__name__]  

# set log level
logger.setLevel[logging.WARNING]

# define file handler and set formatter
file_handler = logging.FileHandler['logfile.log']
formatter    = logging.Formatter['%[asctime]s : %[levelname]s : %[name]s : %[message]s']
file_handler.setFormatter[formatter]

# add file handler to logger
logger.addHandler[file_handler]

# Logs
logger.debug['A debug message']
logger.info['An info message']
logger.warning['Something is not right.']
logger.error['A Major error has happened.']
logger.critical['Fatal error. Cannot continue']

Lưu ý cách chúng tôi đặt bộ định dạng trên ‘_______38_______9‘ chứ không phải trực tiếp trên ‘

import logging

# Gets or creates a logger
logger = logging.getLogger[__name__]  

# set log level
logger.setLevel[logging.WARNING]

# define file handler and set formatter
file_handler = logging.FileHandler['logfile.log']
formatter    = logging.Formatter['%[asctime]s : %[levelname]s : %[name]s : %[message]s']
file_handler.setFormatter[formatter]

# add file handler to logger
logger.addHandler[file_handler]

# Logs
logger.debug['A debug message']
logger.info['An info message']
logger.warning['Something is not right.']
logger.error['A Major error has happened.']
logger.critical['Fatal error. Cannot continue']
0‘

Giả sử đoạn mã trên được chạy từ chương trình chính, nếu bạn nhìn vào bên trong thư mục làm việc, một tệp có tên

import logging

# Gets or creates a logger
logger = logging.getLogger[__name__]  

# set log level
logger.setLevel[logging.WARNING]

# define file handler and set formatter
file_handler = logging.FileHandler['logfile.log']
formatter    = logging.Formatter['%[asctime]s : %[levelname]s : %[name]s : %[message]s']
file_handler.setFormatter[formatter]

# add file handler to logger
logger.addHandler[file_handler]

# Logs
logger.debug['A debug message']
logger.info['An info message']
logger.warning['Something is not right.']
logger.error['A Major error has happened.']
logger.critical['Fatal error. Cannot continue']
1 sẽ được tạo nếu nó không tồn tại và sẽ chứa các thông báo bên dưới

#> 2019-02-17 12:40:14,797 : WARNING : __main__ : Something is not right.
#> 2019-02-17 12:40:14,798 : ERROR : __main__ : A Major error has happened.
#> 2019-02-17 12:40:14,798 : CRITICAL : __main__ : Fatal error. Cannot continue

Lưu ý lại,

logger = logging.getLogger[__name__]
logger.info['my logging message']
8 được đặt trên đối tượng
logger = logging.getLogger[__name__]
logger.info['my logging message']
7 chứ không phải trực tiếp trên logger. Một cái gì đó bạn có thể muốn làm quen với

9. Làm thế nào để bao gồm thông tin truy nguyên trong tin nhắn đã ghi

Bên cạnh các thông báo ‘

import logging

# Gets or creates a logger
logger = logging.getLogger[__name__]  

# set log level
logger.setLevel[logging.WARNING]

# define file handler and set formatter
file_handler = logging.FileHandler['logfile.log']
formatter    = logging.Formatter['%[asctime]s : %[levelname]s : %[name]s : %[message]s']
file_handler.setFormatter[formatter]

# add file handler to logger
logger.addHandler[file_handler]

# Logs
logger.debug['A debug message']
logger.info['An info message']
logger.warning['Something is not right.']
logger.error['A Major error has happened.']
logger.critical['Fatal error. Cannot continue']
4‘, ‘
import logging
logging.basicConfig[level=logging.INFO, file='sample.log']
2‘, ‘
import logging

# Gets or creates a logger
logger = logging.getLogger[__name__]  

# set log level
logger.setLevel[logging.WARNING]

# define file handler and set formatter
file_handler = logging.FileHandler['logfile.log']
formatter    = logging.Formatter['%[asctime]s : %[levelname]s : %[name]s : %[message]s']
file_handler.setFormatter[formatter]

# add file handler to logger
logger.addHandler[file_handler]

# Logs
logger.debug['A debug message']
logger.info['An info message']
logger.warning['Something is not right.']
logger.error['A Major error has happened.']
logger.critical['Fatal error. Cannot continue']
6‘, ‘
import logging

# Gets or creates a logger
logger = logging.getLogger[__name__]  

# set log level
logger.setLevel[logging.WARNING]

# define file handler and set formatter
file_handler = logging.FileHandler['logfile.log']
formatter    = logging.Formatter['%[asctime]s : %[levelname]s : %[name]s : %[message]s']
file_handler.setFormatter[formatter]

# add file handler to logger
logger.addHandler[file_handler]

# Logs
logger.debug['A debug message']
logger.info['An info message']
logger.warning['Something is not right.']
logger.error['A Major error has happened.']
logger.critical['Fatal error. Cannot continue']
7‘ và ‘
import logging

# Gets or creates a logger
logger = logging.getLogger[__name__]  

# set log level
logger.setLevel[logging.WARNING]

# define file handler and set formatter
file_handler = logging.FileHandler['logfile.log']
formatter    = logging.Formatter['%[asctime]s : %[levelname]s : %[name]s : %[message]s']
file_handler.setFormatter[formatter]

# add file handler to logger
logger.addHandler[file_handler]

# Logs
logger.debug['A debug message']
logger.info['An info message']
logger.warning['Something is not right.']
logger.error['A Major error has happened.']
logger.critical['Fatal error. Cannot continue']
8‘, bạn có thể ghi nhật ký các ngoại lệ sẽ bao gồm mọi thông tin truy nguyên liên quan

Với

import logging

# Gets or creates a logger
logger = logging.getLogger[__name__]  

# set log level
logger.setLevel[logging.WARNING]

# define file handler and set formatter
file_handler = logging.FileHandler['logfile.log']
formatter    = logging.Formatter['%[asctime]s : %[levelname]s : %[name]s : %[message]s']
file_handler.setFormatter[formatter]

# add file handler to logger
logger.addHandler[file_handler]

# Logs
logger.debug['A debug message']
logger.info['An info message']
logger.warning['Something is not right.']
logger.error['A Major error has happened.']
logger.critical['Fatal error. Cannot continue']
9, bạn có thể ghi thông tin truy nguyên nếu mã gặp phải bất kỳ lỗi nào.
import logging

# Gets or creates a logger
logger = logging.getLogger[__name__]  

# set log level
logger.setLevel[logging.WARNING]

# define file handler and set formatter
file_handler = logging.FileHandler['logfile.log']
formatter    = logging.Formatter['%[asctime]s : %[levelname]s : %[name]s : %[message]s']
file_handler.setFormatter[formatter]

# add file handler to logger
logger.addHandler[file_handler]

# Logs
logger.debug['A debug message']
logger.info['An info message']
logger.warning['Something is not right.']
logger.error['A Major error has happened.']
logger.critical['Fatal error. Cannot continue']
9 sẽ ghi lại thông báo được cung cấp trong các đối số của nó cũng như thông tin truy nguyên thông báo lỗi

Dưới đây là một ví dụ tốt đẹp

import logging

# Create or get the logger
logger = logging.getLogger[__name__]  

# set log level
logger.setLevel[logging.INFO]

def divide[x, y]:
    try:
        out = x / y
    except ZeroDivisionError:
        logger.exception["Division by zero problem"]
    else:
        return out

# Logs
logger.error["Divide {x} / {y} = {c}".format[x=10, y=0, c=divide[10,0]]]

#> ERROR:__main__:Division by zero problem
#> Traceback [most recent call last]:
#>   File "", line 12, in divide
#>     out = x / y
#> ZeroDivisionError: division by zero
#> ERROR:__main__:None

10. bài tập

  1. Tạo một thư mục dự án mới và một tệp python mới có tên '
    #> 2019-02-17 12:40:14,797 : WARNING : __main__ : Something is not right.
    #> 2019-02-17 12:40:14,798 : ERROR : __main__ : A Major error has happened.
    #> 2019-02-17 12:40:14,798 : CRITICAL : __main__ : Fatal error. Cannot continue
    
    1'. Nhập mô-đun ghi nhật ký và định cấu hình trình ghi nhật ký gốc ở mức thông báo 'gỡ lỗi'. Ghi thông báo 'thông tin' bằng văn bản. “Đây là thông báo ghi nhật ký của trình ghi nhật ký gốc. ”

  2. Định cấu hình trình ghi nhật ký gốc để định dạng thông báo “Đây là thông báo ghi nhật ký của trình ghi nhật ký gốc. " như sau

#> 2019-03-03 17:18:32,703 :: INFO :: Module  :: Line No 1 :: This is root logger's logging message!
Hiển thị giải pháp

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
0

  1. Tạo một tệp python khác trong cùng thư mục có tên là '
    #> 2019-02-17 12:40:14,797 : WARNING : __main__ : Something is not right.
    #> 2019-02-17 12:40:14,798 : ERROR : __main__ : A Major error has happened.
    #> 2019-02-17 12:40:14,798 : CRITICAL : __main__ : Fatal error. Cannot continue
    
    2' và tạo một trình ghi nhật ký mới mang tên mô-đun. Định cấu hình nó ở mức thông báo 'lỗi' và làm cho nó gửi đầu ra nhật ký tới một tệp có tên là “mymod_{current_date}. nhật ký”
  2. Từ trình ghi nhật ký 'mymod' được tạo ở trên, hãy ghi thông báo 'quan trọng' sau vào tệp nhật ký đã nói. “Đây là một thông điệp quan trọng. Đừng phớt lờ nó”

11. Phần kết luận

Xin chúc mừng nếu bạn giải được bài tập

Điều đó khá hữu ích và đơn giản phải không?

ghi nhật ký là một công cụ tuyệt vời nhưng không phổ biến là Quy trình công việc khoa học dữ liệu như nó phải vậy. Tôi hy vọng các khái niệm ghi nhật ký rõ ràng và lần tới khi bạn làm việc với một dự án dựa trên python, yêu cầu của tôi dành cho bạn là hãy nhớ cung cấp cho mô-đun

import logging
logging.basicConfig[level=logging.WARNING]

def hypotenuse[a, b]:
    """Compute the hypotenuse"""
    return [a**2 + b**2]**0.5

kwargs = {'a':3, 'b':4, 'c':hypotenuse[3, 4]}

logging.debug["a = {a}, b = {b}".format[**kwargs]]
logging.info["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]
logging.warning["a={a} and b={b} are equal".format[**kwargs]]
logging.error["a={a} and b={b} cannot be negative".format[**kwargs]]
logging.critical["Hypotenuse of {a}, {b} is {c}".format[**kwargs]]

#> WARNING:root:a=3 and b=3 are equal
#> ERROR:root:a=-1 and b=4 cannot be negative
#> CRITICAL:root:Hypotenuse of a, b is 5.0
5

đăng nhập vui vẻ

Selva Prabhakaran

Selva là Tác giả chính và Biên tập viên của Machine Learning Plus, với hơn 4 triệu độc giả. Anh ấy là tác giả của các khóa học và sách với hơn 100 nghìn sinh viên và là Nhà khoa học dữ liệu chính của một công ty toàn cầu

Sự khác biệt giữa gỡ lỗi và thông tin trong ghi nhật ký Python là gì?

GỠ LỖI. Thông tin thú vị dành cho Nhà phát triển, khi cố gắng gỡ lỗi sự cố. THÔNG TIN. Thông tin thú vị dành cho nhân viên Hỗ trợ đang cố gắng tìm ra ngữ cảnh của một lỗi nhất định. CẢNH BÁO để FATAL. Sự cố và Lỗi tùy theo mức độ hư hỏng

Lợi ích của việc đăng nhập bằng Python là gì?

Ghi nhật ký cho phép bạn thêm ngữ cảnh . ]. Siêu dữ liệu này được thêm tự động mà không cần phải mã cứng nó vào câu lệnh của bạn.

Sự khác biệt giữa ghi nhật ký gỡ lỗi và ghi thông tin là gì?

Trả lời. Thông báo thông tin là thứ mà chúng tôi muốn xem ngay cả khi ứng dụng ở trạng thái tốt nhất. Thông báo GỠ LỖI thường là thứ mà chúng tôi muốn xem khi gỡ lỗi một số vấn đề .

Chủ Đề