{"id":23486875,"url":"https://github.com/zach-taylor/splunk_handler","last_synced_at":"2025-04-05T21:07:00.040Z","repository":{"id":23003638,"uuid":"26354299","full_name":"zach-taylor/splunk_handler","owner":"zach-taylor","description":"Python logging handler for sending logs to Splunk Enterprise","archived":false,"fork":false,"pushed_at":"2024-05-13T11:39:14.000Z","size":132,"stargazers_count":56,"open_issues_count":11,"forks_count":39,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-03-29T20:04:36.332Z","etag":null,"topics":["aws-lambda","logging","python","splunk"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zach-taylor.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-11-08T08:17:46.000Z","updated_at":"2025-03-04T20:49:53.000Z","dependencies_parsed_at":"2024-06-18T22:54:14.602Z","dependency_job_id":null,"html_url":"https://github.com/zach-taylor/splunk_handler","commit_stats":{"total_commits":81,"total_committers":9,"mean_commits":9.0,"dds":0.5802469135802469,"last_synced_commit":"28d64d081a6da0752411ba07094a248773918e5e"},"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zach-taylor%2Fsplunk_handler","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zach-taylor%2Fsplunk_handler/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zach-taylor%2Fsplunk_handler/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zach-taylor%2Fsplunk_handler/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zach-taylor","download_url":"https://codeload.github.com/zach-taylor/splunk_handler/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247399873,"owners_count":20932876,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws-lambda","logging","python","splunk"],"created_at":"2024-12-24T22:17:37.299Z","updated_at":"2025-04-05T21:07:00.018Z","avatar_url":"https://github.com/zach-taylor.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Splunk Handler\n\n[![Build](https://img.shields.io/travis/zach-taylor/splunk_handler.svg?style=flat-square)](https://travis-ci.org/zach-taylor/splunk_handler)\n[![Code Climate](https://img.shields.io/codeclimate/maintainability/zach-taylor/splunk_handler.svg?style=flat-square)](https://codeclimate.com/github/zach-taylor/splunk_handler/maintainability)\n[![PyPI](https://img.shields.io/pypi/v/splunk_handler.svg?style=flat-square)](https://pypi.python.org/pypi/splunk_handler)\n\n**Splunk Handler is a Python Logger for sending logged events to an installation of Splunk Enterprise.**\n\n*This logger requires the destination Splunk Enterprise server to have enabled and configured the [Splunk HTTP Event Collector](http://dev.splunk.com/view/event-collector/SP-CAAAE6M).*\n\n## A Note on Using with AWS Lambda\n\n[AWS Lambda](https://aws.amazon.com/lambda/) has a custom implementation of Python Threading, and does not signal when the main thread exits. Because of this, it is possible to have Lambda halt execution while logs are still being processed. To ensure that execution does not terminate prematurely, Lambda users will be required to invoke splunk_handler.force_flush directly as the very last call in the Lambda handler, which will block the main thread from exiting until all logs have processed.\n~~~python\nfrom splunk_handler import force_flush\n\ndef lambda_handler(event, context):\n    do_work()\n    force_flush()  # Flush logs in a blocking manner\n~~~\n\n\n## Installation\n\nPip:\n\n    pip install splunk_handler\n\nManual:\n\n    python setup.py install\n\n## Usage\n\n    from splunk_handler import SplunkHandler\n\nThen use it like any other regular Python [logging handler](https://docs.python.org/2/howto/logging.html#handlers).\n\nExample:\n\n~~~python\n    import logging\n    from splunk_handler import SplunkHandler\n    splunk = SplunkHandler(\n        host='splunk.example.com',\n        port='8088',\n        token='851A5E58-4EF1-7291-F947-F614A76ACB21',\n        index='main'\n        #allow_overrides=True # whether to look for _\u003cparam in log data (ex: _index)\n        #debug=True # whether to print module activity to stdout, defaults to False\n        #flush_interval=15.0, # send batch of logs every n sec, defaults to 15.0, set '0' to block thread \u0026 send immediately\n        #force_keep_ahead=True # sleep instead of dropping logs when queue fills\n        #hostname='hostname', # manually set a hostname parameter, defaults to socket.gethostname()\n        #protocol='http', # set the protocol which will be used to connect to the splunk host\n        #proxies={\n        #           'http': 'http://10.10.1.10:3128',\n        #           'https': 'http://10.10.1.10:1080',\n        #         }, set the proxies for the session request to splunk host\n        #\n        #queue_size=5000, # a throttle to prevent resource overconsumption, defaults to 5000, set to 0 for no max\n        #record_format=True, whether the log format will be json\n        #retry_backoff=1, the requests lib backoff factor, default options will retry for 1 min, defaults to 2.0\n        #retry_count=5, number of retry attempts on a failed/erroring connection, defaults to 5\n        #source='source', # manually set a source, defaults to the log record.pathname\n        #sourcetype='sourcetype', # manually set a sourcetype, defaults to 'text'\n        #verify=True, # turn SSL verification on or off, defaults to True\n        #timeout=60, # timeout for waiting on a 200 OK from Splunk server, defaults to 60s\n    )\n\n    logging.getLogger('').addHandler(splunk)\n\n    logging.warning('hello!')\n~~~\n\nI would recommend using a JSON formatter with this to receive your logs in JSON format.\nHere is an open source one: https://github.com/madzak/python-json-logger\n\n### Logging Config\n\nSometimes it's a good idea to create a logging configuration using a Python dict\nand the `logging.config.dictConfig` function. This method is used by default in Django.\n\nHere is an example dictionary config and how it might be used in a settings file:\n\n~~~python\nimport os\n\n# Splunk settings\nSPLUNK_HOST = os.getenv('SPLUNK_HOST', 'splunk.example.com')\nSPLUNK_PORT = int(os.getenv('SPLUNK_PORT', '8088'))\nSPLUNK_TOKEN = os.getenv('SPLUNK_TOKEN', '851A5E58-4EF1-7291-F947-F614A76ACB21')\nSPLUNK_INDEX = os.getenv('SPLUNK_INDEX', 'main')\n\nLOGGING = {\n    'version': 1,\n    'disable_existing_loggers': False,\n    'formatters': {\n        'json': {\n            '()': 'pythonjsonlogger.jsonlogger.JsonFormatter',\n            'format': '%(asctime)s %(created)f %(exc_info)s %(filename)s %(funcName)s %(levelname)s %(levelno)s %(lineno)d %(module)s %(message)s %(pathname)s %(process)s %(processName)s %(relativeCreated)d %(thread)s %(threadName)s'\n        }\n    },\n    'handlers': {\n        'splunk': {\n            'level': 'DEBUG',\n            'class': 'splunk_handler.SplunkHandler',\n            'formatter': 'json',\n            'host': SPLUNK_HOST,\n            'port': SPLUNK_PORT,\n            'token': SPLUNK_TOKEN,\n            'index': SPLUNK_INDEX,\n            'sourcetype': 'json',\n        },\n        'console': {\n            'level': 'DEBUG',\n            'class': 'logging.StreamHandler',\n        }\n    },\n    'loggers': {\n        '': {\n            'handlers': ['console', 'splunk'],\n            'level': 'DEBUG'\n        }\n    }\n}\n~~~\n\nThen, do `logging.config.dictConfig(LOGGING)` to configure your logging.\n\nNote: I included a configuration for the JSON formatter mentioned above.\n\nHere is an example file config, and how it might be used in a config file:\n\n~~~\n[loggers]\nkeys=root\n\n[handlers]\nkeys=consoleHandler,splunkHandler\n\n[formatters]\nkeys=simpleFormatter\n\n[logger_root]\nlevel=%(loglevel)s\nhandlers=consoleHandler,splunkHandler\n\n[handler_consoleHandler]\nclass=StreamHandler\nlevel=%(loglevel)s\nformatter=simpleFormatter\nargs=(sys.stdout,)\n\n[handler_splunkHandler]\nclass=splunk_handler.SplunkHandler\nlevel=%(loglevel)s\nformatter=simpleFormatter\nargs=('my-splunk-host.me.com', '', os.environ.get('SPLUNK_TOKEN_DEV', 'changeme'), 'my_index')\nkwargs={'url':'https://my-splunk-host.me.com/services/collector/event', 'verify': False}\n\n[formatter_simpleFormatter]\nformat=[%(asctime)s] %(levelname)s - %(module)s: %(message)s\ndatefmt=%m/%d/%Y %I:%M:%S %p %Z\n\n~~~\n\n## Retry Logic\n\nThis library uses the built-in retry logic from urllib3 (a retry\ncounter and a backoff factor). Should the defaults not be desireable,\nyou can find more information about how to best configure these\nsettings in the [urllib3 documentation](https://github.com/kennethreitz/requests/blob/b2289cd2d5d21bd31cf4a818a4e0ff6951b2317a/requests/packages/urllib3/util/retry.py#L104).\n\n## Contributing\n\nFeel free to contribute an issue or pull request:\n\n1. Check for existing issues and PRs\n2. Fork the repo, and clone it locally\n3. Create a new branch for your contribution\n4. Push to your fork and submit a pull request\n\n## License\n\nThis project is licensed under the terms of the [MIT license](http://opensource.org/licenses/MIT).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzach-taylor%2Fsplunk_handler","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzach-taylor%2Fsplunk_handler","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzach-taylor%2Fsplunk_handler/lists"}