Hướng dẫn python logging to elasticsearch - python ghi nhật ký vào đàn hồi

Hướng dẫn này trình bày cách ăn nhật ký từ ứng dụng Python và cung cấp chúng một cách an toàn vào triển khai dịch vụ elaticsearch. Bạn sẽ thiết lập FileBeat để theo dõi tệp nhật ký có cấu trúc JSON có các trường được định dạng Lược đồ phổ biến (ECS) tiêu chuẩn và sau đó bạn sẽ xem trực quan hóa thời gian thực của các sự kiện nhật ký trong Kibana khi chúng xảy ra. Mặc dù Python được sử dụng cho ví dụ này, cách tiếp cận này để giám sát đầu ra nhật ký được áp dụng trên nhiều loại khách. Kiểm tra danh sách các plugin ghi nhật ký ECS có sẵn.

Bạn sẽ học cách:

  1. Tạo tập lệnh Python với ghi nhật ký
  2. Thiết lập FileBeat
  3. Gửi nhật ký Python đến Elaticsearch
  4. Tạo trực quan hóa nhật ký trong Kibana

Thời gian cần thiết: 1 giờ

Điều kiện tiên quyết

Để hoàn thành các bước này, bạn cần cài đặt Python trên hệ thống của bạn cũng như bộ ghi Lược đồ chung (ECS) đàn hồi cho thư viện ghi nhật ký Python.

Để cài đặt ECS-Logging-Python, Run:

python -m pip install ecs-logging

Nhận elaticsearch ServiceEdit

  1. Nhận một bản dùng thử miễn phí.
  2. Đăng nhập vào đám mây đàn hồi.
  3. Chọn Tạo triển khai.Create deployment.
  4. Đặt tên cho việc triển khai của bạn. Bạn có thể để lại tất cả các cài đặt khác ở các giá trị mặc định của chúng.
  5. Chọn Tạo triển khai và lưu thông tin triển khai đàn hồi của bạn. Bạn sẽ cần những thông tin này sau này.Create deployment and save your Elastic deployment credentials. You will need these credentials later on.

Không muốn đăng ký vào một dịch vụ khác? Bạn cũng có thể nhận dịch vụ Elaticsearch thông qua các thị trường AWS, Azure và GCP.

Kết nối an toàn

Khi kết nối với dịch vụ Elaticsearch, bạn có thể sử dụng ID đám mây để chỉ định chi tiết kết nối. Tìm ID đám mây của bạn bằng cách vào menu chính Kibana và chọn Quản lý> Tích hợp, sau đó chọn chi tiết triển khai xem.

Để kết nối, truyền dữ liệu đến và phát hành các truy vấn với dịch vụ Elaticsearch, bạn cần suy nghĩ về xác thực. Hai cơ chế xác thực được hỗ trợ, khóa API và xác thực cơ bản. Ở đây, để bạn bắt đầu nhanh chóng, chúng tôi sẽ chỉ cho bạn cách sử dụng xác thực cơ bản, nhưng bạn cũng có thể tạo các khóa API như được hiển thị sau. Khóa API an toàn hơn và ưa thích cho môi trường sản xuất.

Tạo tập lệnh Python với Loggedit

Trong bước này, bạn sẽ tạo một tập lệnh Python tạo ra các nhật ký ở định dạng JSON, sử dụng mô -đun ghi nhật ký tiêu chuẩn Python.

  1. Trong một thư mục cục bộ, hãy tạo một tệp mới elvis.py và lưu nó với các nội dung này:

    #!/usr/bin/python
    
    import logging
    import ecs_logging
    import time
    from random import randint
    
    #logger = logging.getLogger(__name__)
    logger = logging.getLogger("app")
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler('elvis.json')
    handler.setFormatter(ecs_logging.StdlibFormatter())
    logger.addHandler(handler)
    
    print("Generating log entries...")
    
    messages = [
        "Elvis has left the building.",#
        "Elvis has left the oven on.",
        "Elvis has two left feet.",
        "Elvis was left out in the cold.",
        "Elvis was left holding the baby.",
        "Elvis left the cake out in the rain.",
        "Elvis came out of left field.",
        "Elvis exited stage left.",
        "Elvis took a left turn.",
        "Elvis left no stone unturned.",
        "Elvis picked up where he left off.",
        "Elvis's train has left the station."
        ]
    
    while True:
        random1 = randint(0,15)
        random2 = randint(1,10)
        if random1 > 11:
            random1 = 0
        if(random1<=4):
            logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=5 and random1<=8):
            logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=9 and random1<=10):
            logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
        else:
            logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
        time.sleep(random2)

    Tập lệnh Python này ngẫu nhiên tạo ra một trong mười hai thông điệp nhật ký, liên tục, ở một khoảng thời gian ngẫu nhiên từ 1 đến 10 giây. Các thông báo nhật ký được ghi vào tệp

    #!/usr/bin/python
    
    import logging
    import ecs_logging
    import time
    from random import randint
    
    #logger = logging.getLogger(__name__)
    logger = logging.getLogger("app")
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler('elvis.json')
    handler.setFormatter(ecs_logging.StdlibFormatter())
    logger.addHandler(handler)
    
    print("Generating log entries...")
    
    messages = [
        "Elvis has left the building.",#
        "Elvis has left the oven on.",
        "Elvis has two left feet.",
        "Elvis was left out in the cold.",
        "Elvis was left holding the baby.",
        "Elvis left the cake out in the rain.",
        "Elvis came out of left field.",
        "Elvis exited stage left.",
        "Elvis took a left turn.",
        "Elvis left no stone unturned.",
        "Elvis picked up where he left off.",
        "Elvis's train has left the station."
        ]
    
    while True:
        random1 = randint(0,15)
        random2 = randint(1,10)
        if random1 > 11:
            random1 = 0
        if(random1<=4):
            logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=5 and random1<=8):
            logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=9 and random1<=10):
            logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
        else:
            logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
        time.sleep(random2)
    1, mỗi thông tin có dấu thời gian, mức độ nhật ký thông tin, cảnh báo, lỗi hoặc dữ liệu quan trọng và dữ liệu khác. Chỉ cần thêm một số phương sai vào dữ liệu nhật ký, thông báo thông tin mà Elvis đã rời khỏi tòa nhà được đặt là sự kiện nhật ký có thể xảy ra nhất.

    Để đơn giản, chỉ có một tệp nhật ký và nó được ghi vào thư mục cục bộ nơi tọa lạc

    #!/usr/bin/python
    
    import logging
    import ecs_logging
    import time
    from random import randint
    
    #logger = logging.getLogger(__name__)
    logger = logging.getLogger("app")
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler('elvis.json')
    handler.setFormatter(ecs_logging.StdlibFormatter())
    logger.addHandler(handler)
    
    print("Generating log entries...")
    
    messages = [
        "Elvis has left the building.",#
        "Elvis has left the oven on.",
        "Elvis has two left feet.",
        "Elvis was left out in the cold.",
        "Elvis was left holding the baby.",
        "Elvis left the cake out in the rain.",
        "Elvis came out of left field.",
        "Elvis exited stage left.",
        "Elvis took a left turn.",
        "Elvis left no stone unturned.",
        "Elvis picked up where he left off.",
        "Elvis's train has left the station."
        ]
    
    while True:
        random1 = randint(0,15)
        random2 = randint(1,10)
        if random1 > 11:
            random1 = 0
        if(random1<=4):
            logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=5 and random1<=8):
            logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=9 and random1<=10):
            logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
        else:
            logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
        time.sleep(random2)
    2. Trong môi trường sản xuất, bạn có thể có nhiều tệp nhật ký, được liên kết với các mô -đun và logger khác nhau và có khả năng được lưu trữ trong
    #!/usr/bin/python
    
    import logging
    import ecs_logging
    import time
    from random import randint
    
    #logger = logging.getLogger(__name__)
    logger = logging.getLogger("app")
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler('elvis.json')
    handler.setFormatter(ecs_logging.StdlibFormatter())
    logger.addHandler(handler)
    
    print("Generating log entries...")
    
    messages = [
        "Elvis has left the building.",#
        "Elvis has left the oven on.",
        "Elvis has two left feet.",
        "Elvis was left out in the cold.",
        "Elvis was left holding the baby.",
        "Elvis left the cake out in the rain.",
        "Elvis came out of left field.",
        "Elvis exited stage left.",
        "Elvis took a left turn.",
        "Elvis left no stone unturned.",
        "Elvis picked up where he left off.",
        "Elvis's train has left the station."
        ]
    
    while True:
        random1 = randint(0,15)
        random2 = randint(1,10)
        if random1 > 11:
            random1 = 0
        if(random1<=4):
            logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=5 and random1<=8):
            logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=9 and random1<=10):
            logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
        else:
            logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
        time.sleep(random2)
    3 hoặc tương tự. Để tìm hiểu thêm về việc định cấu hình đăng nhập vào Python, hãy kiểm tra cơ sở ghi nhật ký cho Python.

    Có nhật ký của bạn được viết theo định dạng JSON với các trường ECS ​​cho phép phân tích và phân tích dễ dàng và để tiêu chuẩn hóa với các ứng dụng khác. Một định dạng tiêu chuẩn, dễ phân tích dễ dàng trở nên ngày càng quan trọng khi khối lượng và loại dữ liệu được ghi lại trong nhật ký của bạn mở rộng theo thời gian.

    Cùng với các trường tiêu chuẩn được bao gồm cho mỗi mục nhập nhật ký là một trường http.request.body.body.content. Trường bổ sung này chỉ để cung cấp cho bạn một số dữ liệu bổ sung, thú vị để làm việc và cũng để chứng minh cách bạn có thể thêm các trường tùy chọn vào dữ liệu nhật ký của mình. Kiểm tra tham chiếu trường ECS ​​để biết danh sách đầy đủ các trường có sẵn.

  2. Hãy để cho kịch bản Python chạy thử. Mở một phiên bản đầu cuối ở vị trí mà bạn đã lưu elvis.py và chạy như sau:

    Sau khi tập lệnh đã chạy trong khoảng 15 giây, hãy nhập Ctrl + C để dừng nó. Hãy xem Elvis.json mới được tạo. Nó nên chứa một hoặc nhiều mục như thế này:

    {"@timestamp":"2021-06-16T02:19:34.687Z","log.level":"info","message":"Elvis has left the building.","ecs":{"version":"1.6.0"},"http":{"request":{"body":{"content":"Elvis has left the building."}}},"log":{"logger":"app","origin":{"file":{"line":39,"name":"elvis.py"},"function":""},"original":"Elvis has left the building."},"process":{"name":"MainProcess","pid":3044,"thread":{"id":4444857792,"name":"MainThread"}}}

  3. Sau khi xác nhận rằng Elvis.py chạy như mong đợi, bạn có thể xóa Elvis.json.

Thiết lập FileBeatedit

FileBeat cung cấp một cách đơn giản, dễ dàng để định cấu hình để giám sát các tệp nhật ký Python của bạn và chuyển dữ liệu nhật ký vào dịch vụ Elaticsearch.

Nhận FileBeat

Tải xuống FileBeat và giải nén nó trên máy chủ cục bộ mà bạn muốn thu thập dữ liệu.

Định cấu hình FileBeat để truy cập dịch vụ elaticsearch

Trong / FileBeat- / (trong đó thư mục trong đó FileBeat được cài đặt và là số phiên bản FileBeat), hãy mở tệp cấu hình FileBeat.yml để chỉnh sửa.

# =============================== Elastic Cloud ================================

# These settings simplify using Filebeat with the Elastic Cloud (https://cloud.elastic.co/).

# The cloud.id setting overwrites the `output.elasticsearch.hosts` and
# `setup.kibana.host` options.
# You can find the `cloud.id` in the Elastic Cloud web UI.
cloud.id: my-deployment:long-hash 

# The cloud.auth setting overwrites the `output.elasticsearch.username` and
# `output.elasticsearch.password` settings. The format is `:`.
cloud.auth: elastic:password 

Giải quyết dòng

#!/usr/bin/python

import logging
import ecs_logging
import time
from random import randint

#logger = logging.getLogger(__name__)
logger = logging.getLogger("app")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('elvis.json')
handler.setFormatter(ecs_logging.StdlibFormatter())
logger.addHandler(handler)

print("Generating log entries...")

messages = [
    "Elvis has left the building.",#
    "Elvis has left the oven on.",
    "Elvis has two left feet.",
    "Elvis was left out in the cold.",
    "Elvis was left holding the baby.",
    "Elvis left the cake out in the rain.",
    "Elvis came out of left field.",
    "Elvis exited stage left.",
    "Elvis took a left turn.",
    "Elvis left no stone unturned.",
    "Elvis picked up where he left off.",
    "Elvis's train has left the station."
    ]

while True:
    random1 = randint(0,15)
    random2 = randint(1,10)
    if random1 > 11:
        random1 = 0
    if(random1<=4):
        logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
    elif(random1>=5 and random1<=8):
        logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
    elif(random1>=9 and random1<=10):
        logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
    else:
        logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
    time.sleep(random2)
4 và thêm ID đám mây triển khai. Bạn có thể bao gồm hoặc bỏ qua: Tiền tố ở đầu ID đám mây. Cả hai phiên bản đều hoạt động tốt. Tìm ID đám mây của bạn bằng cách vào menu chính Kibana và chọn Quản lý> Tích hợp, sau đó chọn chi tiết triển khai xem.

Khởi động dòng

#!/usr/bin/python

import logging
import ecs_logging
import time
from random import randint

#logger = logging.getLogger(__name__)
logger = logging.getLogger("app")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('elvis.json')
handler.setFormatter(ecs_logging.StdlibFormatter())
logger.addHandler(handler)

print("Generating log entries...")

messages = [
    "Elvis has left the building.",#
    "Elvis has left the oven on.",
    "Elvis has two left feet.",
    "Elvis was left out in the cold.",
    "Elvis was left holding the baby.",
    "Elvis left the cake out in the rain.",
    "Elvis came out of left field.",
    "Elvis exited stage left.",
    "Elvis took a left turn.",
    "Elvis left no stone unturned.",
    "Elvis picked up where he left off.",
    "Elvis's train has left the station."
    ]

while True:
    random1 = randint(0,15)
    random2 = randint(1,10)
    if random1 > 11:
        random1 = 0
    if(random1<=4):
        logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
    elif(random1>=5 and random1<=8):
        logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
    elif(random1>=9 and random1<=10):
        logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
    else:
        logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
    time.sleep(random2)
5 và thêm tên người dùng và mật khẩu cho việc triển khai mà bạn đã ghi khi bạn tạo triển khai. Định dạng là:, ví dụ đàn hồi: 57UGJ782KVKWMSKG8UVE.

Định cấu hình đầu vào FileBeat

FileBeat có một số cách để thu thập nhật ký. Đối với ví dụ này, bạn sẽ định cấu hình bộ sưu tập nhật ký theo cách thủ công.

Trong phần FileBeat.Inputs của FileBeat.yml, đặt đã bật: thành đúng và đặt đường dẫn: đến vị trí của tệp nhật ký hoặc tệp của bạn. Trong ví dụ này, đặt cùng một thư mục trong đó bạn đã lưu elvis.py:

filebeat.inputs:

# Each - is an input. Most options can be set at the input level, so
# you can use different inputs for various configurations.
# Below are the input specific configurations.

- type: log

  # Change to true to enable this input configuration.
  enabled: true

  # Paths that should be crawled and fetched. Glob based paths.
  paths:
    - /path/to/log/files/*.json

Bạn có thể chỉ định ký tự ký tự đại diện (*) để chỉ ra rằng tất cả các tệp nhật ký trong thư mục được chỉ định nên được đọc. Bạn cũng có thể sử dụng ký tự đại diện để đọc nhật ký từ nhiều thư mục. Ví dụ

#!/usr/bin/python

import logging
import ecs_logging
import time
from random import randint

#logger = logging.getLogger(__name__)
logger = logging.getLogger("app")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('elvis.json')
handler.setFormatter(ecs_logging.StdlibFormatter())
logger.addHandler(handler)

print("Generating log entries...")

messages = [
    "Elvis has left the building.",#
    "Elvis has left the oven on.",
    "Elvis has two left feet.",
    "Elvis was left out in the cold.",
    "Elvis was left holding the baby.",
    "Elvis left the cake out in the rain.",
    "Elvis came out of left field.",
    "Elvis exited stage left.",
    "Elvis took a left turn.",
    "Elvis left no stone unturned.",
    "Elvis picked up where he left off.",
    "Elvis's train has left the station."
    ]

while True:
    random1 = randint(0,15)
    random2 = randint(1,10)
    if random1 > 11:
        random1 = 0
    if(random1<=4):
        logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
    elif(random1>=5 and random1<=8):
        logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
    elif(random1>=9 and random1<=10):
        logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
    else:
        logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
    time.sleep(random2)
6.

Thêm các tùy chọn đầu vào JSON

Tùy chọn cấu hình đầu vào FileBeat, bao gồm một số cài đặt để giải mã các thông báo JSON. Các tệp nhật ký được giải mã theo từng dòng, do đó, điều quan trọng là chúng có chứa một đối tượng JSON trên mỗi dòng.

Đối với ví dụ này, FileBeat sử dụng bốn tùy chọn giải mã sau đây.

  json.keys_under_root: true
  json.overwrite_keys: true
  json.add_error_key: true
  json.expand_keys: true

Để tìm hiểu thêm về các cài đặt này, hãy kiểm tra các tùy chọn cấu hình đầu vào JSON và giải mã các trường JSON trong tham chiếu FileBeat.

Nối bốn tùy chọn giải mã JSON vào phần đầu vào FileBeat của FileBeat.yml, để phần này trông như thế này:

# ============================== Filebeat inputs ===============================

filebeat.inputs:

# Each - is an input. Most options can be set at the input level, so
# you can use different inputs for various configurations.
# Below are the input specific configurations.

- type: log

  # Change to true to enable this input configuration.
  enabled: true

  # Paths that should be crawled and fetched. Glob based paths.
  paths:
    - /path/to/log/files/*.json
  json.keys_under_root: true
  json.overwrite_keys: true
  json.add_error_key: true
  json.expand_keys: true

Kết thúc việc thiết lập FileBeat

FileBeat đi kèm với các tài sản được xác định trước để phân tích cú pháp, lập chỉ mục và trực quan hóa dữ liệu của bạn. Để tải các tài sản này, hãy chạy các tài sản sau từ thư mục cài đặt FileBeat:

Tùy thuộc vào các biến bao gồm vị trí cài đặt, môi trường và quyền cục bộ, bạn có thể cần thay đổi quyền sở hữu của FileBeat.yml. Bạn cũng có thể thử chạy lệnh dưới dạng root: sudo ./filebeat setup -e hoặc bạn có thể vô hiệu hóa kiểm tra quyền nghiêm ngặt bằng cách chạy lệnh với tùy chọn

#!/usr/bin/python

import logging
import ecs_logging
import time
from random import randint

#logger = logging.getLogger(__name__)
logger = logging.getLogger("app")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('elvis.json')
handler.setFormatter(ecs_logging.StdlibFormatter())
logger.addHandler(handler)

print("Generating log entries...")

messages = [
    "Elvis has left the building.",#
    "Elvis has left the oven on.",
    "Elvis has two left feet.",
    "Elvis was left out in the cold.",
    "Elvis was left holding the baby.",
    "Elvis left the cake out in the rain.",
    "Elvis came out of left field.",
    "Elvis exited stage left.",
    "Elvis took a left turn.",
    "Elvis left no stone unturned.",
    "Elvis picked up where he left off.",
    "Elvis's train has left the station."
    ]

while True:
    random1 = randint(0,15)
    random2 = randint(1,10)
    if random1 > 11:
        random1 = 0
    if(random1<=4):
        logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
    elif(random1>=5 and random1<=8):
        logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
    elif(random1>=9 and random1<=10):
        logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
    else:
        logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
    time.sleep(random2)
7.

Quá trình thiết lập mất vài phút. Nếu mọi thứ diễn ra thành công, bạn sẽ nhận được tin nhắn xác nhận:

Chế độ xem dữ liệu FileBeat (trước đây là mẫu chỉ mục) hiện có sẵn trong ElaticSearch. Để xác minh:

Bắt đầu với Phiên bản Stack 8.0, các mẫu chỉ số Kibana đã được đổi tên thành các chế độ xem dữ liệu. Để tìm hiểu thêm, hãy kiểm tra Kibana những gì mới trong trang 8.0.

  1. Đăng nhập vào Kibana.
  2. Mở menu chính Kibana và chọn Quản lý ngăn xếp, sau đó xem dữ liệu.Stack Management, then Data views.
  3. Trong thanh tìm kiếm, tìm kiếm FileBeat. Bạn nên nhận FileBeat-* trong kết quả tìm kiếm.

Tùy chọn: Sử dụng khóa API để xác thực

Để bảo mật bổ sung, thay vì sử dụng xác thực cơ bản, bạn có thể tạo khóa API Elaticsearch thông qua bảng điều khiển dịch vụ Elaticsearch, sau đó định cấu hình FileBeat để sử dụng khóa mới để kết nối an toàn với triển khai dịch vụ elaticsearch.

  1. Đăng nhập vào bảng điều khiển dịch vụ elaticsearch.
  2. Tìm triển khai của bạn trên trang chủ trong thẻ dịch vụ Elaticsearch và nhấp vào biểu tượng bánh răng để truy cập trực tiếp. Hoặc, chọn Dịch vụ Elaticsearch để truy cập trang triển khai để xem tất cả các triển khai của bạn.
  3. Trên trang triển khai, bạn có thể thu hẹp triển khai của mình theo tên, ID hoặc chọn từ một số bộ lọc khác. Để tùy chỉnh chế độ xem của bạn, sử dụng kết hợp các bộ lọc hoặc thay đổi định dạng từ lưới sang danh sách.
  4. Từ menu triển khai của bạn, chọn Elaticsearch, sau đó là bảng điều khiển API.Elasticsearch, then API console.
  5. Chọn bài viết từ danh sách thả xuống và nhập
    #!/usr/bin/python
    
    import logging
    import ecs_logging
    import time
    from random import randint
    
    #logger = logging.getLogger(__name__)
    logger = logging.getLogger("app")
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler('elvis.json')
    handler.setFormatter(ecs_logging.StdlibFormatter())
    logger.addHandler(handler)
    
    print("Generating log entries...")
    
    messages = [
        "Elvis has left the building.",#
        "Elvis has left the oven on.",
        "Elvis has two left feet.",
        "Elvis was left out in the cold.",
        "Elvis was left holding the baby.",
        "Elvis left the cake out in the rain.",
        "Elvis came out of left field.",
        "Elvis exited stage left.",
        "Elvis took a left turn.",
        "Elvis left no stone unturned.",
        "Elvis picked up where he left off.",
        "Elvis's train has left the station."
        ]
    
    while True:
        random1 = randint(0,15)
        random2 = randint(1,10)
        if random1 > 11:
            random1 = 0
        if(random1<=4):
            logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=5 and random1<=8):
            logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=9 and random1<=10):
            logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
        else:
            logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
        time.sleep(random2)
    8 trong trường.Post from the drop-down list and enter
    #!/usr/bin/python
    
    import logging
    import ecs_logging
    import time
    from random import randint
    
    #logger = logging.getLogger(__name__)
    logger = logging.getLogger("app")
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler('elvis.json')
    handler.setFormatter(ecs_logging.StdlibFormatter())
    logger.addHandler(handler)
    
    print("Generating log entries...")
    
    messages = [
        "Elvis has left the building.",#
        "Elvis has left the oven on.",
        "Elvis has two left feet.",
        "Elvis was left out in the cold.",
        "Elvis was left holding the baby.",
        "Elvis left the cake out in the rain.",
        "Elvis came out of left field.",
        "Elvis exited stage left.",
        "Elvis took a left turn.",
        "Elvis left no stone unturned.",
        "Elvis picked up where he left off.",
        "Elvis's train has left the station."
        ]
    
    while True:
        random1 = randint(0,15)
        random2 = randint(1,10)
        if random1 > 11:
            random1 = 0
        if(random1<=4):
            logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=5 and random1<=8):
            logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=9 and random1<=10):
            logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
        else:
            logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
        time.sleep(random2)
    8 in the field.
  6. Nhập yêu cầu sau:

    {
     "name": "filebeat-api-key",
     "role_descriptors": {
       "logstash_read_write": {
         "cluster": ["manage_index_templates", "monitor"],
         "index": [
           {
             "names": ["filebeat-*"],
             "privileges": ["create_index", "write", "read", "manage"]
           }
         ]
       }
     }
    }

    Điều này tạo ra khóa API với đặc quyền cụm

    #!/usr/bin/python
    
    import logging
    import ecs_logging
    import time
    from random import randint
    
    #logger = logging.getLogger(__name__)
    logger = logging.getLogger("app")
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler('elvis.json')
    handler.setFormatter(ecs_logging.StdlibFormatter())
    logger.addHandler(handler)
    
    print("Generating log entries...")
    
    messages = [
        "Elvis has left the building.",#
        "Elvis has left the oven on.",
        "Elvis has two left feet.",
        "Elvis was left out in the cold.",
        "Elvis was left holding the baby.",
        "Elvis left the cake out in the rain.",
        "Elvis came out of left field.",
        "Elvis exited stage left.",
        "Elvis took a left turn.",
        "Elvis left no stone unturned.",
        "Elvis picked up where he left off.",
        "Elvis's train has left the station."
        ]
    
    while True:
        random1 = randint(0,15)
        random2 = randint(1,10)
        if random1 > 11:
            random1 = 0
        if(random1<=4):
            logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=5 and random1<=8):
            logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
        elif(random1>=9 and random1<=10):
            logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
        else:
            logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
        time.sleep(random2)
    9 cho phép truy cập chỉ đọc để xác định trạng thái cụm và
    {"@timestamp":"2021-06-16T02:19:34.687Z","log.level":"info","message":"Elvis has left the building.","ecs":{"version":"1.6.0"},"http":{"request":{"body":{"content":"Elvis has left the building."}}},"log":{"logger":"app","origin":{"file":{"line":39,"name":"elvis.py"},"function":""},"original":"Elvis has left the building."},"process":{"name":"MainProcess","pid":3044,"thread":{"id":4444857792,"name":"MainThread"}}}
    0 cho phép tất cả các hoạt động trên các mẫu chỉ mục. Một số đặc quyền bổ sung cũng cho phép các hoạt động
    {"@timestamp":"2021-06-16T02:19:34.687Z","log.level":"info","message":"Elvis has left the building.","ecs":{"version":"1.6.0"},"http":{"request":{"body":{"content":"Elvis has left the building."}}},"log":{"logger":"app","origin":{"file":{"line":39,"name":"elvis.py"},"function":""},"original":"Elvis has left the building."},"process":{"name":"MainProcess","pid":3044,"thread":{"id":4444857792,"name":"MainThread"}}}
    1,
    {"@timestamp":"2021-06-16T02:19:34.687Z","log.level":"info","message":"Elvis has left the building.","ecs":{"version":"1.6.0"},"http":{"request":{"body":{"content":"Elvis has left the building."}}},"log":{"logger":"app","origin":{"file":{"line":39,"name":"elvis.py"},"function":""},"original":"Elvis has left the building."},"process":{"name":"MainProcess","pid":3044,"thread":{"id":4444857792,"name":"MainThread"}}}
    2 và
    {"@timestamp":"2021-06-16T02:19:34.687Z","log.level":"info","message":"Elvis has left the building.","ecs":{"version":"1.6.0"},"http":{"request":{"body":{"content":"Elvis has left the building."}}},"log":{"logger":"app","origin":{"file":{"line":39,"name":"elvis.py"},"function":""},"original":"Elvis has left the building."},"process":{"name":"MainProcess","pid":3044,"thread":{"id":4444857792,"name":"MainThread"}}}
    3 cho chỉ mục được chỉ định. Đặc quyền
    {"@timestamp":"2021-06-16T02:19:34.687Z","log.level":"info","message":"Elvis has left the building.","ecs":{"version":"1.6.0"},"http":{"request":{"body":{"content":"Elvis has left the building."}}},"log":{"logger":"app","origin":{"file":{"line":39,"name":"elvis.py"},"function":""},"original":"Elvis has left the building."},"process":{"name":"MainProcess","pid":3044,"thread":{"id":4444857792,"name":"MainThread"}}}
    3 được thêm vào để cho phép làm mới chỉ mục.

  7. Chọn Gửi. Đầu ra phải tương tự như sau:Submit. The output should be similar to the following:

    {
      "api_key": "tV1dnfF-GHI59ykgv4N0U3",
      "id": "2TBR42gBabmINotmvZjv",
      "name": "filebeat-api-key"
    }

  8. Thêm thông tin chính API của bạn vào phần đầu ra của ElaticSearch của
    {"@timestamp":"2021-06-16T02:19:34.687Z","log.level":"info","message":"Elvis has left the building.","ecs":{"version":"1.6.0"},"http":{"request":{"body":{"content":"Elvis has left the building."}}},"log":{"logger":"app","origin":{"file":{"line":39,"name":"elvis.py"},"function":""},"original":"Elvis has left the building."},"process":{"name":"MainProcess","pid":3044,"thread":{"id":4444857792,"name":"MainThread"}}}
    5, ngay dưới đầu ra.elaticsearch:. Sử dụng định dạng
    {"@timestamp":"2021-06-16T02:19:34.687Z","log.level":"info","message":"Elvis has left the building.","ecs":{"version":"1.6.0"},"http":{"request":{"body":{"content":"Elvis has left the building."}}},"log":{"logger":"app","origin":{"file":{"line":39,"name":"elvis.py"},"function":""},"original":"Elvis has left the building."},"process":{"name":"MainProcess","pid":3044,"thread":{"id":4444857792,"name":"MainThread"}}}
    6. Nếu kết quả của bạn như thể hiện trong ví dụ này, hãy nhập
    {"@timestamp":"2021-06-16T02:19:34.687Z","log.level":"info","message":"Elvis has left the building.","ecs":{"version":"1.6.0"},"http":{"request":{"body":{"content":"Elvis has left the building."}}},"log":{"logger":"app","origin":{"file":{"line":39,"name":"elvis.py"},"function":""},"original":"Elvis has left the building."},"process":{"name":"MainProcess","pid":3044,"thread":{"id":4444857792,"name":"MainThread"}}}
    7.
  9. Thêm một dấu hiệu (

    {"@timestamp":"2021-06-16T02:19:34.687Z","log.level":"info","message":"Elvis has left the building.","ecs":{"version":"1.6.0"},"http":{"request":{"body":{"content":"Elvis has left the building."}}},"log":{"logger":"app","origin":{"file":{"line":39,"name":"elvis.py"},"function":""},"original":"Elvis has left the building."},"process":{"name":"MainProcess","pid":3044,"thread":{"id":4444857792,"name":"MainThread"}}}
    8) để nhận xét về đám mây.Auth: đàn hồi: dòng, vì FileBeat sẽ sử dụng khóa API thay vì tên người dùng và mật khẩu triển khai để xác thực.

    # =============================== Elastic Cloud ================================
    
    # These settings simplify using Filebeat with the Elastic Cloud (https://cloud.elastic.co/).
    
    # The cloud.id setting overwrites the `output.elasticsearch.hosts` and
    # `setup.kibana.host` options.
    # You can find the `cloud.id` in the Elastic Cloud web UI.
    cloud.id: my-deployment:yTMtd5VzdKEuP2NwPbNsb3VkLtKzLmldJDcyMzUyNjBhZGP7MjQ4OTZiNTIxZTQyOPY2C2NeOGQwJGQ2YWQ4M5FhNjIyYjQ9ODZhYWNjKDdlX2Yz4ELhRYJ7
    
    # The cloud.auth setting overwrites the `output.elasticsearch.username` and
    # `output.elasticsearch.password` settings. The format is `:`.
    #cloud.auth: elastic:591KhtuAgTP46by9C4EmhGuk
    
    # ================================== Outputs ===================================
    
    # Configure what output to use when sending the data collected by the beat.
    
    # ---------------------------- Elasticsearch Output ----------------------------
    output.elasticsearch:
      # Array of hosts to connect to.
      api_key: "2TBR42gBabmINotmvZjv:tV1dnfF-GHI59ykgv4N0U3"

Gửi nhật ký Python đến Elaticsearchedit

Đó là thời gian để gửi một số dữ liệu nhật ký vào Elaticsearch!

Khởi chạy FileBeat và Elvis.py

Khởi chạy FileBeat bằng cách chạy các phần sau từ thư mục cài đặt FileBeat:

#!/usr/bin/python

import logging
import ecs_logging
import time
from random import randint

#logger = logging.getLogger(__name__)
logger = logging.getLogger("app")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('elvis.json')
handler.setFormatter(ecs_logging.StdlibFormatter())
logger.addHandler(handler)

print("Generating log entries...")

messages = [
    "Elvis has left the building.",#
    "Elvis has left the oven on.",
    "Elvis has two left feet.",
    "Elvis was left out in the cold.",
    "Elvis was left holding the baby.",
    "Elvis left the cake out in the rain.",
    "Elvis came out of left field.",
    "Elvis exited stage left.",
    "Elvis took a left turn.",
    "Elvis left no stone unturned.",
    "Elvis picked up where he left off.",
    "Elvis's train has left the station."
    ]

while True:
    random1 = randint(0,15)
    random2 = randint(1,10)
    if random1 > 11:
        random1 = 0
    if(random1<=4):
        logger.info(messages[random1], extra={"http.request.body.content": messages[random1]})
    elif(random1>=5 and random1<=8):
        logger.warning(messages[random1], extra={"http.request.body.content": messages[random1]})
    elif(random1>=9 and random1<=10):
        logger.error(messages[random1], extra={"http.request.body.content": messages[random1]})
    else:
        logger.critical(messages[random1], extra={"http.request.body.content": messages[random1]})
    time.sleep(random2)
0

Trong lệnh này:

  • Cờ -E gửi đầu ra đến lỗi tiêu chuẩn thay vì đầu ra nhật ký được định cấu hình.
  • Cờ -C chỉ định đường dẫn đến tệp cấu hình FileBeat.

Chỉ trong trường hợp lệnh không hoạt động như mong đợi, hãy kiểm tra FileBeat nhanh bắt đầu cho cú pháp lệnh chi tiết cho hệ điều hành của bạn. Bạn cũng có thể thử chạy lệnh dưới dạng root: sudo ./filebeat -e -c filebeat.yml.

FileBeat hiện nên chạy và theo dõi nội dung của Elvis.json, mà thực sự không tồn tại. Vì vậy, hãy để tạo ra nó. Mở một phiên bản đầu cuối mới và chạy tập lệnh elvis.py Python:

Hãy để kịch bản chạy trong vài phút và có thể pha cà phê nhanh hoặc trà. Sau đó, đảm bảo rằng tệp elvis.json được tạo như mong đợi và được điền với một số mục nhật ký.

Xác minh các mục nhật ký trong dịch vụ elaticsearch

Bước tiếp theo là xác nhận rằng dữ liệu nhật ký đã tìm thấy thành công nó vào dịch vụ Elaticsearch.

  1. Đăng nhập vào Kibana.
  2. Mở menu chính Kibana và chọn Quản lý ngăn xếp, sau đó xem dữ liệu.Stack Management, then Data views.
  3. Trong thanh tìm kiếm, tìm kiếm *fileBeat_. Bạn nên nhận FileBeat-* trong kết quả tìm kiếm.
  4. Chọn FileBeat-*.

Chế độ xem dữ liệu FileBeat hiển thị một danh sách các trường và chi tiết của chúng.

Tạo trực quan hóa nhật ký trong kibanaedit

Bây giờ, thời gian để tạo trực quan hóa dựa trên dữ liệu nhật ký ứng dụng Python.

  1. Mở menu chính Kibana và chọn bảng điều khiển, sau đó tạo bảng điều khiển.Dashboard, then Create dashboard.
  2. Chọn Tạo trực quan. Trình chỉnh sửa trực quan ống kính mở ra.Create visualization. The Lens visualization editor opens.
  3. Trong hộp Data View Dropdown, chọn FileBeat-, nếu nó không được chọn.filebeat-, if it isn’t already selected.
  4. Trong hộp thả xuống loại biểu đồ, chọn thanh dọc xếp chồng lên nhau, nếu nó đã được chọn.CHART TYPE dropdown box, select Bar vertical stacked, if it isn’t already selected.
  5. Kiểm tra xem bộ lọc thời gian được đặt thành 15 phút kéo dài.Last 15 minutes.
  6. Từ danh sách các trường có sẵn, kéo và thả trường @timestamp vào trình tạo trực quan.Available fields list, drag and drop the @timestamp field onto the visualization builder.
  7. Kéo và thả trường Log.level vào Trình tạo trực quan.
  8. Trong khu vực Cài đặt Biểu đồ, dưới sự phá vỡ, chọn các giá trị hàng đầu của log.level và đặt số lượng giá trị thành 4. Vì có bốn mức độ nghiêm trọng của nhật ký, tham số này đặt tất cả chúng xuất hiện trong huyền thoại biểu đồ.Break down by, select Top values of log.level and set Number of values to 4. Since there are four log severity levels, this parameter sets all of them to appear in the chart legend.
  9. Chọn Làm mới. Một biểu đồ thanh xếp chồng hiện cho thấy tần số tương đối của mỗi trong số bốn mức độ nghiêm trọng của nhật ký theo thời gian.Refresh. A stacked bar chart now shows the relative frequency of each of the four log severity levels over time.

    Hướng dẫn python logging to elasticsearch - python ghi nhật ký vào đàn hồi

  10. Chọn Lưu và trả lại để thêm trực quan hóa này vào bảng điều khiển của bạn.Save and return to add this visualization to your dashboard.

Hãy để tạo ra một hình ảnh thứ hai.

  1. Chọn Tạo trực quan.Create visualization.
  2. Một lần nữa, hãy chắc chắn rằng loại biểu đồ được đặt thành thanh dọc xếp chồng lên nhau.CHART TYPE is set to Bar vertical stacked.
  3. Từ danh sách các trường có sẵn, kéo và thả trường @timestamp vào trình tạo trực quan.Available fields list, drag and drop the @timestamp field onto the visualization builder.
  4. Kéo và thả trường Log.level vào Trình tạo trực quan.http.request.body.content field onto the visualization builder.
  5. Trong khu vực Cài đặt Biểu đồ, dưới sự phá vỡ, chọn các giá trị hàng đầu của log.level và đặt số lượng giá trị thành 4. Vì có bốn mức độ nghiêm trọng của nhật ký, tham số này đặt tất cả chúng xuất hiện trong huyền thoại biểu đồ.Break down by, select Top values of http.request.body.content and set Number of values to 12. Since there are twelve different log messages, this parameter sets all of them to appear in the chart legend.
  6. Chọn Làm mới. Một biểu đồ thanh xếp chồng hiện cho thấy tần số tương đối của mỗi trong số bốn mức độ nghiêm trọng của nhật ký theo thời gian.Refresh. A stacked bar chart now shows the relative frequency of each of the log messages over time.

    Hướng dẫn python logging to elasticsearch - python ghi nhật ký vào đàn hồi

  7. Chọn Lưu và trả lại để thêm trực quan hóa này vào bảng điều khiển của bạn.Save and return to add this visualization to your dashboard.

Hãy để tạo ra một hình ảnh thứ hai.

  1. Chọn Tạo trực quan.Create visualization.
  2. Một lần nữa, hãy chắc chắn rằng loại biểu đồ được đặt thành thanh dọc xếp chồng lên nhau.CHART TYPE dropdown box, select Donut.
  3. Kéo và thả trường http.request.body.content vào trình tạo trực quan.log.level field onto the visualization builder. A donut chart appears.

    Hướng dẫn python logging to elasticsearch - python ghi nhật ký vào đàn hồi

  4. Chọn Lưu và trả lại để thêm trực quan hóa này vào bảng điều khiển của bạn.Save and return to add this visualization to your dashboard.
  5. Hãy để tạo ra một hình ảnh thứ hai.Save and add a title to save your new dashboard.

Chọn Tạo trực quan.

Một lần nữa, hãy chắc chắn rằng loại biểu đồ được đặt thành thanh dọc xếp chồng lên nhau.

Kéo và thả trường http.request.body.content vào trình tạo trực quan.

  1. Trong khu vực Cài đặt biểu đồ, dưới sự phá vỡ, chọn các giá trị hàng đầu của http.request.body.content và đặt số lượng giá trị thành 12. Vì có mười hai tin nhắn nhật ký khác nhau, tham số này đặt tất cả chúng xuất hiện trong Truyền thuyết biểu đồ .Refresh on the Kibana dashboard. Since elvis.py continues to run and generate log data, your Kibana visualizations update with each refresh.

    Hướng dẫn python logging to elasticsearch - python ghi nhật ký vào đàn hồi

  2. Chọn Làm mới. Một biểu đồ thanh xếp chồng hiện cho thấy tần số tương đối của từng thông báo nhật ký theo thời gian.

Và bây giờ cho hình ảnh cuối cùng.