From e35700ff74114fcd96ffdb8d5c02ee8954321c96 Mon Sep 17 00:00:00 2001 From: Djcarrillo6 Date: Sun, 12 Nov 2023 20:25:28 -0800 Subject: [PATCH 1/3] Added a guide & sample for a custom logger client implementation. Signed-off-by: Djcarrillo6 Black formatter Signed-off-by: Djcarrillo6 --- CHANGELOG.md | 1 + guides/log_collection.md | 131 +++++++++++++++++++++++ samples/logging/log_collection_sample.py | 107 ++++++++++++++++++ 3 files changed, 239 insertions(+) create mode 100644 guides/log_collection.md create mode 100644 samples/logging/log_collection_sample.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b0af7511..a45ab3a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) - Added `samples`, `benchmarks` and `docs` to `nox -rs format` ([#556](https://github.com/opensearch-project/opensearch-py/pull/556)) - Added guide on the document lifecycle API(s) ([#559](https://github.com/opensearch-project/opensearch-py/pull/559)) - Added Windows CI ([#569](https://github.com/opensearch-project/opensearch-py/pull/569)) +- Added guide on using a Python logging integration with OpenSearch logs ([#]()) ### Changed - Generate `tasks` client from API specs ([#508](https://github.com/opensearch-project/opensearch-py/pull/508)) - Generate `ingest` client from API specs ([#513](https://github.com/opensearch-project/opensearch-py/pull/513)) diff --git a/guides/log_collection.md b/guides/log_collection.md new file mode 100644 index 00000000..25029886 --- /dev/null +++ b/guides/log_collection.md @@ -0,0 +1,131 @@ +# Log Collection Guide + - [Import Required Modules](#import-required-modules) + - [Setup Connection with OpenSearch Cluster](#setup-connection-with-opensearch-cluster) + - [Initialize Logger](#initialize-logger) + - [Define Custom Handler for OpenSearch](#define-custom-handler-for-opensearch) + - [Create OpenSearch Handler and Add to Logger](#create-opensearch-handler-and-add-to-logger) + - [Setup Asynchronous Logging Using Queues](#setup-asynchronous-logging-using-queues) + - [Clean Up](#clean-up) + +# Log Collection Guide +In this guide, we will look at how to collect logs from your application and send them to OpenSearch. + +# Import Required Modules +Let's import the required modules: + +```python +import urllib3 +urllib3.disable_warnings() +from datetime import datetime +import logging +import queue +from opensearchpy import OpenSearch +from logging.handlers import QueueHandler, QueueListener +``` + +# Setup Connection with OpenSearch Cluster +Let's create a client instance: + +```python +opensearch_client = OpenSearch( + "https://admin:admin@localhost:9200", + use_ssl=True, + verify_certs=False, + ssl_show_warn=False, + http_auth=("admin", "admin") +) +``` + +# Initialize Logger +Now, let's initialize a logger named "OpenSearchLogs" for OpenSearch and set the log level to INFO: + +```python +# Initialize a logger named "OpenSearchLogs" for OpenSearch & set log level to INFO +print("Initializing logger...") +os_logger = logging.getLogger("OpenSearchLogs") +os_logger.setLevel(logging.INFO) +``` + +# Define Custom Handler for OpenSearch +Next, let's define a custom handler that logs to OpenSearch: + +```python +# Define a custom handler that logs to OpenSearch +class OpenSearchHandler(logging.Handler): + # Initializer / Instance attributes + def __init__(self, opensearch_client): + logging.Handler.__init__(self) + self.os_client = opensearch_client + + # Build index name (e.g., "logs-YYYY-MM-DD") + def _build_index_name(self): + return f"logs-{datetime.date(datetime.now())}" + + # Emit logs to the OpenSearch cluster + def emit(self, record): + document = { + "timestamp": datetime.fromtimestamp(record.created).isoformat(), + "name": record.name, + "level": record.levelname, + "message": record.getMessage(), + "source": { + "file": record.pathname, + "line": record.lineno, + "function": record.funcName + }, + "process": { + "id": record.process, + "name": record.processName + }, + "thread": { + "id": record.thread, + "name": record.threadName + } + } + + # Write the log entry to OpenSearch, handle exceptions + try: + self.os_client.index(index="movies", id=1, body={'title': 'Beauty and the Beast', 'year': 1991}) + except Exception as e: + print(f"Failed to send log to OpenSearch: {e}") +``` + +# Create OpenSearch Handler and Add to Logger +Now, let's create an instance of OpenSearchHandler and add it to the logger: + +```python +print("Creating an instance of OpenSearchHandler and adding it to the logger...") +# Create an instance of OpenSearchHandler and add it to the logger +os_handler = OpenSearchHandler(opensearch_client) +os_logger.addHandler(os_handler) +``` + +# Setup Asynchronous Logging Using Queues +Finally, let's setup asynchronous logging using Queues: + +```python +print("Setting up asynchronous logging using Queues...") +# Setup asynchronous logging using Queues +log_queue = queue.Queue(-1) # no limit on size +os_queue_handler = QueueHandler(log_queue) +os_queue_listener = QueueListener(log_queue, os_handler) + +# Add queue handler to the logger +os_logger.addHandler(os_queue_handler) + +# Start listening on the queue using the os_queue_listener +os_queue_listener.start() +``` + +# Clean Up +Finally, let's clean up by stopping the queue listener: + +```python +print("Cleaning up...") +# Stop listening on the queue +os_queue_listener.stop() +print("Log Collection Guide has completed running") +``` + +# Sample Code +See [log_collection_sample.py](/samples/logging/log_collection_sample.py) for a working sample of the concepts in this guide. \ No newline at end of file diff --git a/samples/logging/log_collection_sample.py b/samples/logging/log_collection_sample.py new file mode 100644 index 00000000..4c9149ae --- /dev/null +++ b/samples/logging/log_collection_sample.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python + +# -*- coding: utf-8 -*- +# SPDX-License-Identifier: Apache-2.0 +# +# The OpenSearch Contributors require contributions made to +# this file be licensed under the Apache-2.0 license or a +# compatible open source license. +# +# Modifications Copyright OpenSearch Contributors. See +# GitHub history for details. + +from datetime import datetime +import logging +import queue +from opensearchpy import OpenSearch +from logging.handlers import QueueHandler, QueueListener + +# For cleaner output, comment in the two lines below to disable warnings and informational messages +# import urllib3 +# urllib3.disable_warnings() + + +def run_log_collection_guide() -> None: + print("Running Log Collection Guide") + + # Setup connection with the OpenSearch cluster + print("Setting up connection with OpenSearch cluster...") + opensearch_client = OpenSearch( + "https://admin:admin@localhost:9200", + use_ssl=True, + verify_certs=False, + ssl_show_warn=False, + http_auth=("admin", "admin"), + ) + + # Initialize a logger named "OpenSearchLogs" for OpenSearch + print("Initializing logger...") + os_logger = logging.getLogger("OpenSearchLogs") + os_logger.setLevel(logging.INFO) + + # Define a custom handler that logs to OpenSearch + class OpenSearchHandler(logging.Handler): + # Initializer / Instance attributes + def __init__(self, opensearch_client): + logging.Handler.__init__(self) + self.os_client = opensearch_client + + # Build index name (e.g., "logs-YYYY-MM-DD") + def _build_index_name(self): + return f"logs-{datetime.date(datetime.now())}" + + # Emit logs to the OpenSearch cluster + def emit(self, record): + document = { + "timestamp": datetime.fromtimestamp(record.created).isoformat(), + "name": record.name, + "level": record.levelname, + "message": record.getMessage(), + "source": { + "file": record.pathname, + "line": record.lineno, + "function": record.funcName, + }, + "process": {"id": record.process, "name": record.processName}, + "thread": {"id": record.thread, "name": record.threadName}, + } + + # Write the log entry to OpenSearch, handle exceptions + try: + self.os_client.index( + index="movies", + id=1, + body={"title": "Beauty and the Beast", "year": 1991}, + ) + except Exception as e: + print(f"Failed to send log to OpenSearch: {e}") + + print("Creating an instance of OpenSearchHandler and adding it to the logger...") + # Create an instance of OpenSearchHandler and add it to the logger + os_handler = OpenSearchHandler(opensearch_client) + os_logger.addHandler(os_handler) + + print("Setting up asynchronous logging using Queues...") + # Setup asynchronous logging using Queues + log_queue = queue.Queue(-1) # no limit on size + os_queue_handler = QueueHandler(log_queue) + os_queue_listener = QueueListener(log_queue, os_handler) + + # Add queue handler to the logger + os_logger.addHandler(os_queue_handler) + + # Start listening on the queue using the os_queue_listener + os_queue_listener.start() + + print("Logger is set up and listener has started. Sending a test log...") + # Logging a test message + os_logger.info("This is a test log message") + + print("Cleaning up...") + # Stop listening on the queue + os_queue_listener.stop() + print("Log Collection Guide has completed running") + + +if __name__ == "__main__": + run_log_collection_guide() From 18373d1086d186974b3071b36f299e100beb7fb3 Mon Sep 17 00:00:00 2001 From: Djcarrillo6 Date: Thu, 16 Nov 2023 17:59:25 -0800 Subject: [PATCH 2/3] Changes from PR review Signed-off-by: Djcarrillo6 Fixed import formatting in sample code for gudie. Signed-off-by: Djcarrillo6 Fixed nox formatting of log collection sample module. Signed-off-by: Djcarrillo6 Added types to log_collection_sample.py Signed-off-by: Djcarrillo6 Added type ignore to StramHandler class Signed-off-by: Djcarrillo6 Added formatting change Signed-off-by: Djcarrillo6 --- CHANGELOG.md | 2 +- guides/log_collection.md | 122 +++++++++++++---------- samples/logging/log_collection_sample.py | 39 +++++--- 3 files changed, 96 insertions(+), 67 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 059d3021..ee76d493 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,7 +34,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) - Added guide on the document lifecycle API(s) ([#559](https://github.com/opensearch-project/opensearch-py/pull/559)) - Added Windows CI ([#569](https://github.com/opensearch-project/opensearch-py/pull/569)) - Added `client.http` JSON REST request API helpers ([#544](https://github.com/opensearch-project/opensearch-py/pull/544)) -- Added guide on using a Python logging integration with OpenSearch logs ([#579](https://github.com/opensearch-project/opensearch-py/pull/579)) +- Added guide on using a custom Python logging integration with OpenSearch logs ([#579](https://github.com/opensearch-project/opensearch-py/pull/579)) ### Changed - Generate `tasks` client from API specs ([#508](https://github.com/opensearch-project/opensearch-py/pull/508)) - Generate `ingest` client from API specs ([#513](https://github.com/opensearch-project/opensearch-py/pull/513)) diff --git a/guides/log_collection.md b/guides/log_collection.md index 25029886..af83f467 100644 --- a/guides/log_collection.md +++ b/guides/log_collection.md @@ -23,75 +23,82 @@ from opensearchpy import OpenSearch from logging.handlers import QueueHandler, QueueListener ``` -# Setup Connection with OpenSearch Cluster -Let's create a client instance: +# Setup Connection with OpenSearch +Run the following commands to install the docker image: +``` +docker pull opensearchproject/opensearch:latest +``` + +Create a client instance: ```python -opensearch_client = OpenSearch( - "https://admin:admin@localhost:9200", - use_ssl=True, - verify_certs=False, - ssl_show_warn=False, - http_auth=("admin", "admin") +client = OpenSearch( + hosts=['https://@localhost:9200'], + use_ssl=True, + verify_certs=False, + http_auth=('admin', 'admin') ) ``` # Initialize Logger -Now, let's initialize a logger named "OpenSearchLogs" for OpenSearch and set the log level to INFO: +Set the OpenSearch logger level top INFO: ```python # Initialize a logger named "OpenSearchLogs" for OpenSearch & set log level to INFO print("Initializing logger...") os_logger = logging.getLogger("OpenSearchLogs") os_logger.setLevel(logging.INFO) + +# Create a console handler +console_handler = logging.StreamHandler() +console_handler.setLevel(logging.INFO) + +# Add console handler to the logger +os_logger.addHandler(console_handler) ``` -# Define Custom Handler for OpenSearch -Next, let's define a custom handler that logs to OpenSearch: +# Custom Handler For Logs +Define a custom handler that logs to OpenSearch: ```python -# Define a custom handler that logs to OpenSearch class OpenSearchHandler(logging.Handler): - # Initializer / Instance attributes - def __init__(self, opensearch_client): - logging.Handler.__init__(self) - self.os_client = opensearch_client - - # Build index name (e.g., "logs-YYYY-MM-DD") - def _build_index_name(self): - return f"logs-{datetime.date(datetime.now())}" - - # Emit logs to the OpenSearch cluster - def emit(self, record): - document = { - "timestamp": datetime.fromtimestamp(record.created).isoformat(), - "name": record.name, - "level": record.levelname, - "message": record.getMessage(), - "source": { - "file": record.pathname, - "line": record.lineno, - "function": record.funcName - }, - "process": { - "id": record.process, - "name": record.processName - }, - "thread": { - "id": record.thread, - "name": record.threadName - } - } - - # Write the log entry to OpenSearch, handle exceptions - try: - self.os_client.index(index="movies", id=1, body={'title': 'Beauty and the Beast', 'year': 1991}) - except Exception as e: - print(f"Failed to send log to OpenSearch: {e}") + # Initializer / Instance attributes + def __init__(self, opensearch_client): + logging.Handler.__init__(self) + self.os_client = opensearch_client + + # Build index name (e.g., "logs-YYYY-MM-DD") + def _build_index_name(self): + return f"logs-{datetime.date(datetime.now())}" + + # Emit logs to the OpenSearch cluster + def emit(self, record): + document = { + "timestamp": datetime.fromtimestamp(record.created).isoformat(), + "name": record.name, + "level": record.levelname, + "message": record.getMessage(), + "source": { + "file": record.pathname, + "line": record.lineno, + "function": record.funcName, + }, + "process": {"id": record.process, "name": record.processName}, + "thread": {"id": record.thread, "name": record.threadName}, + } + + # Write the log entry to OpenSearch, handle exceptions + try: + self.os_client.index( + index=self._build_index_name(), + body=document, + ) + except Exception as e: + print(f"Failed to send log to OpenSearch: {e}") ``` # Create OpenSearch Handler and Add to Logger -Now, let's create an instance of OpenSearchHandler and add it to the logger: +Create an instance of OpenSearchHandler and add it to the logger: ```python print("Creating an instance of OpenSearchHandler and adding it to the logger...") @@ -128,4 +135,19 @@ print("Log Collection Guide has completed running") ``` # Sample Code -See [log_collection_sample.py](/samples/logging/log_collection_sample.py) for a working sample of the concepts in this guide. \ No newline at end of file +See [log_collection_sample.py](/samples/logging/log_collection_sample.py) for a working sample of the concepts in this guide. This Python script is a guide for setting up and running a custom log collection system using the OpenSearch service. The script will create a logger named "OpenSearchLogs" and set the log level to INFO. It will then create an instance of OpenSearchHandler and add it to the logger. Finally, it will setup asynchronous logging using Queues and send a test log to the OpenSearch cluster. + +Exptected Output From Running [log_collection_sample.py](/samples/logging/log_collection_sample.py): +```python +""" + Running Log Collection Guide + Setting up connection with OpenSearch cluster... + Initializing logger... + Creating an instance of OpenSearchHandler and adding it to the logger... + Setting up asynchronous logging using Queues... + Logger is set up and listener has started. Sending a test log... + This is a test log message + Cleaning up... + Log Collection Guide has completed running +""" +``` \ No newline at end of file diff --git a/samples/logging/log_collection_sample.py b/samples/logging/log_collection_sample.py index 4c9149ae..0303eede 100644 --- a/samples/logging/log_collection_sample.py +++ b/samples/logging/log_collection_sample.py @@ -10,11 +10,13 @@ # Modifications Copyright OpenSearch Contributors. See # GitHub history for details. -from datetime import datetime import logging import queue -from opensearchpy import OpenSearch +from datetime import datetime from logging.handlers import QueueHandler, QueueListener +from typing import Any + +from opensearchpy import OpenSearch # For cleaner output, comment in the two lines below to disable warnings and informational messages # import urllib3 @@ -24,9 +26,13 @@ def run_log_collection_guide() -> None: print("Running Log Collection Guide") + # Create a console handler + console_handler: logging.StreamHandler = logging.StreamHandler() # type: ignore + console_handler.setLevel(logging.INFO) + # Setup connection with the OpenSearch cluster print("Setting up connection with OpenSearch cluster...") - opensearch_client = OpenSearch( + opensearch_client: Any = OpenSearch( "https://admin:admin@localhost:9200", use_ssl=True, verify_certs=False, @@ -36,22 +42,25 @@ def run_log_collection_guide() -> None: # Initialize a logger named "OpenSearchLogs" for OpenSearch print("Initializing logger...") - os_logger = logging.getLogger("OpenSearchLogs") + os_logger: logging.Logger = logging.getLogger("OpenSearchLogs") os_logger.setLevel(logging.INFO) + # Add console handler to the logger + os_logger.addHandler(console_handler) + # Define a custom handler that logs to OpenSearch class OpenSearchHandler(logging.Handler): # Initializer / Instance attributes - def __init__(self, opensearch_client): - logging.Handler.__init__(self) + def __init__(self, opensearch_client: Any) -> None: + super().__init__() self.os_client = opensearch_client # Build index name (e.g., "logs-YYYY-MM-DD") - def _build_index_name(self): + def _build_index_name(self) -> str: return f"logs-{datetime.date(datetime.now())}" # Emit logs to the OpenSearch cluster - def emit(self, record): + def emit(self, record: logging.LogRecord) -> None: document = { "timestamp": datetime.fromtimestamp(record.created).isoformat(), "name": record.name, @@ -66,26 +75,24 @@ def emit(self, record): "thread": {"id": record.thread, "name": record.threadName}, } - # Write the log entry to OpenSearch, handle exceptions try: self.os_client.index( - index="movies", - id=1, - body={"title": "Beauty and the Beast", "year": 1991}, + index=self._build_index_name(), + body=document, ) except Exception as e: print(f"Failed to send log to OpenSearch: {e}") print("Creating an instance of OpenSearchHandler and adding it to the logger...") # Create an instance of OpenSearchHandler and add it to the logger - os_handler = OpenSearchHandler(opensearch_client) + os_handler: OpenSearchHandler = OpenSearchHandler(opensearch_client) os_logger.addHandler(os_handler) print("Setting up asynchronous logging using Queues...") # Setup asynchronous logging using Queues - log_queue = queue.Queue(-1) # no limit on size - os_queue_handler = QueueHandler(log_queue) - os_queue_listener = QueueListener(log_queue, os_handler) + log_queue: queue.Queue[logging.LogRecord] = queue.Queue(-1) # no limit on size + os_queue_handler: logging.Handler = QueueHandler(log_queue) + os_queue_listener: QueueListener = QueueListener(log_queue, os_handler) # Add queue handler to the logger os_logger.addHandler(os_queue_handler) From 580e2c2f4547f4a788edd032843cb0cbb8fdffcd Mon Sep 17 00:00:00 2001 From: Djcarrillo6 Date: Sun, 19 Nov 2023 11:02:23 -0800 Subject: [PATCH 3/3] Added PR review changes. Signed-off-by: Djcarrillo6 Fixed typo in CHANGELOG. Signed-off-by: Djcarrillo6 Requested changes. Signed-off-by: Djcarrillo6 Requested changes again. Signed-off-by: Djcarrillo6 Added link in USER_GUIDE.md. Signed-off-by: Djcarrillo6 --- CHANGELOG.md | 2 +- USER_GUIDE.md | 1 + guides/log_collection.md | 178 ++++++++++++----------- samples/logging/log_collection_sample.py | 14 +- 4 files changed, 107 insertions(+), 88 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3544e378..b8c2e3c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ## [Unreleased] ### Added +- Added a log collection guide ([#579](https://github.com/opensearch-project/opensearch-py/pull/579)) ### Changed ### Deprecated ### Removed @@ -37,7 +38,6 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) - Added guide on the document lifecycle API(s) ([#559](https://github.com/opensearch-project/opensearch-py/pull/559)) - Added Windows CI ([#569](https://github.com/opensearch-project/opensearch-py/pull/569)) - Added `client.http` JSON REST request API helpers ([#544](https://github.com/opensearch-project/opensearch-py/pull/544)) -- Added guide on using a custom Python logging integration with OpenSearch logs ([#579](https://github.com/opensearch-project/opensearch-py/pull/579)) ### Changed - Generate `tasks` client from API specs ([#508](https://github.com/opensearch-project/opensearch-py/pull/508)) - Generate `ingest` client from API specs ([#513](https://github.com/opensearch-project/opensearch-py/pull/513)) diff --git a/USER_GUIDE.md b/USER_GUIDE.md index 84fe4d5b..78aa6656 100644 --- a/USER_GUIDE.md +++ b/USER_GUIDE.md @@ -158,6 +158,7 @@ print(response) - [Making Raw JSON REST Requests](guides/json.md) - [Connection Classes](guides/connection_classes.md) - [Document Lifecycle](guides/document_lifecycle.md) +- [Collecting Logs](guides/log_collection.md) ## Plugins diff --git a/guides/log_collection.md b/guides/log_collection.md index af83f467..ed07c4da 100644 --- a/guides/log_collection.md +++ b/guides/log_collection.md @@ -1,63 +1,75 @@ -# Log Collection Guide - - [Import Required Modules](#import-required-modules) - - [Setup Connection with OpenSearch Cluster](#setup-connection-with-opensearch-cluster) - - [Initialize Logger](#initialize-logger) - - [Define Custom Handler for OpenSearch](#define-custom-handler-for-opensearch) - - [Create OpenSearch Handler and Add to Logger](#create-opensearch-handler-and-add-to-logger) - - [Setup Asynchronous Logging Using Queues](#setup-asynchronous-logging-using-queues) - - [Clean Up](#clean-up) - -# Log Collection Guide +- [Log Collection Guide](#log-collection-guide) +- [Import Required Modules](#import-required-modules) +- [Download and Start OpenSearch](#download-and-start-opensearch) +- [Setup Connection with OpenSearch](#setup-connection-with-opensearch) +- [Initialize Logger](#initialize-logger) +- [Custom Handler For Logs](#custom-handler-for-logs) +- [Create OpenSearch Handler and Add to Logger](#create-opensearch-handler-and-add-to-logger) +- [Setup Asynchronous Logging Using Queues](#setup-asynchronous-logging-using-queues) +- [Clean Up](#clean-up) +- [Sample Code](#sample-code) + + +## Log Collection Guide In this guide, we will look at how to collect logs from your application and send them to OpenSearch. -# Import Required Modules +## Import Required Modules Let's import the required modules: ```python -import urllib3 -urllib3.disable_warnings() -from datetime import datetime import logging import queue -from opensearchpy import OpenSearch +from datetime import datetime from logging.handlers import QueueHandler, QueueListener -``` +from typing import Any -# Setup Connection with OpenSearch +import urllib3 + +from opensearchpy import OpenSearch -Run the following commands to install the docker image: +urllib3.disable_warnings() +``` + +## Download and Start OpenSearch ``` docker pull opensearchproject/opensearch:latest ``` +``` +docker run -d -p 9200:9200 -p 9600:9600 --name opensearch_opensearch_1 -e "discovery.type=single-node" opensearchproject/opensearch:latest +``` + +## Setup Connection with OpenSearch + Create a client instance: ```python -client = OpenSearch( - hosts=['https://@localhost:9200'], - use_ssl=True, - verify_certs=False, - http_auth=('admin', 'admin') -) + opensearch_client: Any = OpenSearch( + "https://admin:admin@localhost:9200", + use_ssl=True, + verify_certs=False, + ssl_show_warn=False, + http_auth=("admin", "admin"), + ) ``` -# Initialize Logger -Set the OpenSearch logger level top INFO: +## Initialize Logger +Initialize a logger, named "OpenSearchLogs", that emits logs to OpenSearch, and a console handler, both set to the INFO level, are initialized. The console handler is then added to the logger. For every log line processed by this setup, a corresponding OpenSearch document is created. This approach supports structured and comprehensive logging because each document can include extensive metadata within it. ```python -# Initialize a logger named "OpenSearchLogs" for OpenSearch & set log level to INFO -print("Initializing logger...") -os_logger = logging.getLogger("OpenSearchLogs") -os_logger.setLevel(logging.INFO) + # Initialize a logger named "OpenSearchLogs" for OpenSearch & set log level to INFO + print("Initializing logger...") + os_logger = logging.getLogger("OpenSearchLogs") + os_logger.setLevel(logging.INFO) -# Create a console handler -console_handler = logging.StreamHandler() -console_handler.setLevel(logging.INFO) + # Create a console handler + console_handler = logging.StreamHandler() + console_handler.setLevel(logging.INFO) -# Add console handler to the logger -os_logger.addHandler(console_handler) + # Add console handler to the logger + os_logger.addHandler(console_handler) ``` -# Custom Handler For Logs +## Custom Handler For Logs Define a custom handler that logs to OpenSearch: ```python @@ -65,7 +77,7 @@ class OpenSearchHandler(logging.Handler): # Initializer / Instance attributes def __init__(self, opensearch_client): logging.Handler.__init__(self) - self.os_client = opensearch_client + self.opensearch_client = opensearch_client # Build index name (e.g., "logs-YYYY-MM-DD") def _build_index_name(self): @@ -83,71 +95,75 @@ class OpenSearchHandler(logging.Handler): "line": record.lineno, "function": record.funcName, }, - "process": {"id": record.process, "name": record.processName}, - "thread": {"id": record.thread, "name": record.threadName}, + "process": { + "id": record.process, + "name": record.processName + }, + "thread": { + "id": record.thread, + "name": record.threadName + }, } - # Write the log entry to OpenSearch, handle exceptions - try: - self.os_client.index( - index=self._build_index_name(), - body=document, - ) - except Exception as e: - print(f"Failed to send log to OpenSearch: {e}") + # Write the log entry to OpenSearch, handle exceptions + self.opensearch_client.index( + index=self._build_index_name(), + body=document, + ) ``` -# Create OpenSearch Handler and Add to Logger +## Create OpenSearch Handler and Add to Logger Create an instance of OpenSearchHandler and add it to the logger: ```python -print("Creating an instance of OpenSearchHandler and adding it to the logger...") -# Create an instance of OpenSearchHandler and add it to the logger -os_handler = OpenSearchHandler(opensearch_client) -os_logger.addHandler(os_handler) + print("Creating an instance of OpenSearchHandler and adding it to the logger...") + # Create an instance of OpenSearchHandler and add it to the logger + os_handler = OpenSearchHandler(opensearch_client) + os_logger.addHandler(os_handler) ``` -# Setup Asynchronous Logging Using Queues +## Setup Asynchronous Logging Using Queues Finally, let's setup asynchronous logging using Queues: ```python -print("Setting up asynchronous logging using Queues...") -# Setup asynchronous logging using Queues -log_queue = queue.Queue(-1) # no limit on size -os_queue_handler = QueueHandler(log_queue) -os_queue_listener = QueueListener(log_queue, os_handler) + print("Setting up asynchronous logging using Queues...") + # Setup asynchronous logging using Queues + log_queue = queue.Queue(-1) # no limit on size + os_queue_handler = QueueHandler(log_queue) + os_queue_listener = QueueListener(log_queue, os_handler) -# Add queue handler to the logger -os_logger.addHandler(os_queue_handler) + # Add queue handler to the logger + os_logger.addHandler(os_queue_handler) -# Start listening on the queue using the os_queue_listener -os_queue_listener.start() + # Start listening on the queue using the os_queue_listener + os_queue_listener.start() ``` -# Clean Up +## Clean Up Finally, let's clean up by stopping the queue listener: ```python -print("Cleaning up...") -# Stop listening on the queue -os_queue_listener.stop() -print("Log Collection Guide has completed running") + print("Cleaning up...") + # Stop listening on the queue + os_queue_listener.stop() + print("Log Collection Guide has completed running") ``` -# Sample Code -See [log_collection_sample.py](/samples/logging/log_collection_sample.py) for a working sample of the concepts in this guide. This Python script is a guide for setting up and running a custom log collection system using the OpenSearch service. The script will create a logger named "OpenSearchLogs" and set the log level to INFO. It will then create an instance of OpenSearchHandler and add it to the logger. Finally, it will setup asynchronous logging using Queues and send a test log to the OpenSearch cluster. +## Sample Code +See [log_collection_sample.py](/samples/logging/log_collection_sample.py) for a working sample of the concepts in this guide. The script will create a logger named "OpenSearchLogs" and set the log level to INFO. It will then create an instance of OpenSearchHandler and add it to the logger. Finally, it will setup asynchronous logging using Queues and send a test log to the OpenSearch cluster. Exptected Output From Running [log_collection_sample.py](/samples/logging/log_collection_sample.py): -```python -""" - Running Log Collection Guide - Setting up connection with OpenSearch cluster... - Initializing logger... - Creating an instance of OpenSearchHandler and adding it to the logger... - Setting up asynchronous logging using Queues... - Logger is set up and listener has started. Sending a test log... - This is a test log message - Cleaning up... - Log Collection Guide has completed running -""" + +``` + """ + Running Log Collection Guide + Setting up connection with OpenSearch cluster... + Initializing logger... + Creating an instance of OpenSearchHandler and adding it to the logger... + Setting up asynchronous logging using Queues... + Logger is set up and listener has started. Sending a test log... + This is a test log message + Cleaning up... + Log Collection Guide has completed running + """ ``` \ No newline at end of file diff --git a/samples/logging/log_collection_sample.py b/samples/logging/log_collection_sample.py index 0303eede..1e85b977 100644 --- a/samples/logging/log_collection_sample.py +++ b/samples/logging/log_collection_sample.py @@ -16,15 +16,15 @@ from logging.handlers import QueueHandler, QueueListener from typing import Any +import urllib3 + from opensearchpy import OpenSearch -# For cleaner output, comment in the two lines below to disable warnings and informational messages -# import urllib3 -# urllib3.disable_warnings() +urllib3.disable_warnings() -def run_log_collection_guide() -> None: - print("Running Log Collection Guide") +def main() -> None: + print("Collecting logs.") # Create a console handler console_handler: logging.StreamHandler = logging.StreamHandler() # type: ignore @@ -82,6 +82,8 @@ def emit(self, record: logging.LogRecord) -> None: ) except Exception as e: print(f"Failed to send log to OpenSearch: {e}") + logging.warning(f"Failed to send log to OpenSearch: {e}") + raise print("Creating an instance of OpenSearchHandler and adding it to the logger...") # Create an instance of OpenSearchHandler and add it to the logger @@ -111,4 +113,4 @@ def emit(self, record: logging.LogRecord) -> None: if __name__ == "__main__": - run_log_collection_guide() + main()