Skip to content

Commit

Permalink
Merge pull request #257 from phenobarbital/logstash-handler
Browse files Browse the repository at this point in the history
Logstash Handler Configuration (working example)
  • Loading branch information
phenobarbital authored May 30, 2023
2 parents b689865 + c131b15 commit a01843c
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 38 deletions.
9 changes: 6 additions & 3 deletions examples/test_logstash.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
## set a new logger name
logger.setName('config.example')
# verbose debugging:
logger.verbose('This is a verbose message')
logger.verbose(
'Working Example',
extra={"custom_name": "example", "ipaddr": "90.71.169.159"}
)

# Give Elasticsearch some time to index the new log entry
sleep(5)
Expand All @@ -19,12 +22,12 @@
# Define the search query
search_query = {
"match": {
"message": "This is a verbose message"
"message": "Working Example"
}
}

# Perform the search
res = es.search(index="logstash-*", query=search_query)
res = es.search(index="logdb", query=search_query)


# Extract the total number of hits
Expand Down
47 changes: 13 additions & 34 deletions navconfig/logging/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@
root={
'handlers': ['ErrorFileHandler'],
'level': loglevel,
'propagate': True,
},
)

Expand Down Expand Up @@ -165,43 +166,21 @@
if logging_echo is True:
logging_config['root']['handlers'].append('console')

if logstash_logging:
if logstash_logging is True:
logging.debug(
"Logstash configuration Enabled."
)
environment = config.ENV if config.ENV is not None else 'production'
# basic configuration of Logstash
try:
import logstash_async # pylint: disable=W0611
except ImportError as ex:
raise RuntimeError(
"NavConfig: Logstash Logging is enabled but Logstash async \
dependency is not installed.\
Hint: run 'pip install logstash_async'."
) from ex
LOGSTASH_HOST = config.get('LOGSTASH_HOST', fallback='localhost')
LOGSTASH_PORT = config.getint('LOGSTASH_PORT', fallback=6000)
LOG_TAG = config.get('FLUENT_TAG', fallback='app.log')
logging_config['formatters']['logstash'] = {
'()': 'logstash_async.formatter.LogstashFormatter',
'message_type': 'python-logstash',
'fqdn': False, # Fully qualified domain name. Default value: false.
'extra_prefix': 'dev',
'extra': {
'application': f'{APP_NAME}',
'project_path': f'{BASE_DIR}',
'environment': environment
}
}
logging_config['handlers']['LogstashHandler'] = {
'class': 'logstash_async.handler.AsynchronousLogstashHandler',
'formatter': 'logstash',
'transport': 'logstash_async.transport.TcpTransport',
'host': LOGSTASH_HOST,
'port': int(LOGSTASH_PORT),
'level': loglevel,
'database_path': f'{LOG_DIR}/logstash.db',
}
### Importing Logstash Handler and returning Logging Config:
from .handlers import LogstashHandler
lh = LogstashHandler(
config=config
)
logging_config['formatters']['logstash'] = lh.formatter(
application=APP_NAME, path=BASE_DIR
)
logging_config['handlers']['LogstashHandler'] = lh.handler(
loglevel=loglevel, propagate=True
)
if 'root' not in logging_config:
logging_config['root'] = {}
if 'handlers' not in logging_config['root']:
Expand Down
1 change: 1 addition & 0 deletions navconfig/logging/handlers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .logstash import LogstashHandler
54 changes: 54 additions & 0 deletions navconfig/logging/handlers/logstash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# basic configuration of Logstash
try:
import logstash_async # pylint: disable=W0611
except ImportError as ex:
raise RuntimeError(
"NavConfig: Logstash Logging is enabled but Logstash async \
dependency is not installed.\
Hint: run 'pip install logstash_async'."
) from ex


class LogstashHandler:
def __init__(self, config) -> None:
self.env = config.ENV if config.ENV is not None else 'production'
self.host = config.get('LOGSTASH_HOST', fallback='127.0.0.1')
self.port = config.getint('LOGSTASH_PORT', fallback=6000)

def formatter(
self,
application: str,
path: str,
fqdn: bool = False,
**kwargs
):
return {
'()': 'logstash_async.formatter.LogstashFormatter',
'message_type': 'python-logstash',
'fqdn': fqdn,
"extra_prefix": 'dev',
'extra': {
'application': f'{application}',
'project_path': f'{path}',
'environment': self.env,
**kwargs
}
}

def handler(self, loglevel, enable_localdb: bool = False, **kwargs):
hdlr = {
'class': 'logstash_async.handler.AsynchronousLogstashHandler',
'formatter': 'logstash',
'transport': 'logstash_async.transport.TcpTransport',
'host': self.host,
'port': int(self.port),
'level': loglevel
}
if enable_localdb is True:
log_dir = kwargs['logdir']
hdlr['database_path'] = f'{log_dir}/logstash.db'
else:
hdlr['database_path'] = ''
if 'propagate' in kwargs:
hdlr['propagate'] = kwargs['propagate']
return hdlr
2 changes: 1 addition & 1 deletion navconfig/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
__title__ = 'navconfig'
__description__ = ('Configuration tool for all Navigator Services '
'Tool for accessing Config info from different sources.')
__version__ = '1.2.1'
__version__ = '1.2.2'
__author__ = 'Jesus Lara'
__author_email__ = '[email protected]'
__license__ = 'MIT'

0 comments on commit a01843c

Please sign in to comment.