- Notifications
You must be signed in to change notification settings - Fork5.5k
Add support for JSON formatted logs#5799
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
13 commits Select commitHold shift + click to select a range
1929fb5 Add support for JSON formatted logs
mriedemb617d91 Check for json log formatting in log_request
mriedemca95490 Add log_json config option with default and validation handling
mriedem6a74393 Pass NotebookApp logger to log_request
mriedem3e32ce5 Cleanup for log_json review
mriedem47e06b0 Log request properties separately when log_json=True
mriedem8b06db3 Address review comments
mriedemfac2285 Fix logging in _validate_log_json
mriedem093aee2 Add some basic tests for log_json config
mriedem08f8ccd Add log_json=True test for log_request
mriedem4ee4bb2 Use unittest assertion methods for improved logging
mriedem6a883e0 Fix NotebookAppJSONLoggingTests.test_log_json_enabled
mriedem67ad5a1 Merge remote-tracking branch 'origin/master' into 5798-json-logging
mriedemFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
26 changes: 16 additions & 10 deletionsnotebook/log.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
43 changes: 42 additions & 1 deletionnotebook/notebookapp.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -8,6 +8,7 @@ | ||
| import binascii | ||
| import datetime | ||
| import errno | ||
| import functools | ||
| import gettext | ||
| import hashlib | ||
| import hmac | ||
| @@ -247,9 +248,12 @@ def init_settings(self, jupyter_app, kernel_manager, contents_manager, | ||
| # collapse $HOME to ~ | ||
| root_dir = '~' + root_dir[len(home):] | ||
| # Use the NotebookApp logger and its formatting for tornado request logging. | ||
| log_function = functools.partial( | ||
| log_request, log=log, log_json=jupyter_app.log_json) | ||
kevin-bates marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| settings = dict( | ||
| # basics | ||
| log_function=log_function, | ||
| base_url=base_url, | ||
| default_url=default_url, | ||
| template_path=template_path, | ||
| @@ -701,6 +705,43 @@ class NotebookApp(JupyterApp): | ||
| _log_formatter_cls = LogFormatter | ||
| _json_logging_import_error_logged = False | ||
| log_json = Bool(False, config=True, | ||
mriedem marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| help=_('Set to True to enable JSON formatted logs. ' | ||
| 'Run "pip install notebook[json-logging]" to install the ' | ||
| 'required dependent packages. Can also be set using the ' | ||
| 'environment variable JUPYTER_ENABLE_JSON_LOGGING=true.') | ||
| ) | ||
| @default('log_json') | ||
| def _default_log_json(self): | ||
| """Get the log_json value from the environment.""" | ||
| return os.getenv('JUPYTER_ENABLE_JSON_LOGGING', 'false').lower() == 'true' | ||
| @validate('log_json') | ||
| def _validate_log_json(self, proposal): | ||
| # If log_json=True, see if the json_logging package can be imported and | ||
| # override _log_formatter_cls if so. | ||
| value = proposal['value'] | ||
| if value: | ||
| try: | ||
| import json_logging | ||
| self.log.debug('initializing json logging') | ||
blink1073 marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| json_logging.init_non_web(enable_json=True) | ||
| self._log_formatter_cls = json_logging.JSONLogFormatter | ||
| except ImportError: | ||
| # If configured for json logs and we can't do it, log a hint. | ||
| # Only log the error once though. | ||
| if not self._json_logging_import_error_logged: | ||
| self.log.warning( | ||
| 'Unable to use json logging due to missing packages. ' | ||
| 'Run "pip install notebook[json-logging]" to fix.' | ||
| ) | ||
| self._json_logging_import_error_logged = True | ||
| value = False | ||
| return value | ||
| @default('log_level') | ||
| def _default_log_level(self): | ||
| return logging.INFO | ||
40 changes: 40 additions & 0 deletionsnotebook/tests/test_log.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| import unittest | ||
| from unittest import mock | ||
| from notebook import log | ||
| class TestLogRequest(unittest.TestCase): | ||
| @mock.patch('notebook.log.prometheus_log_method') | ||
| def test_log_request_json(self, mock_prometheus): | ||
| headers = {'Referer': 'test'} | ||
| request = mock.Mock( | ||
| request_time=mock.Mock(return_value=1), | ||
| headers=headers, | ||
| method='GET', | ||
| remote_ip='1.2.3.4', | ||
| uri='/notebooks/foo/bar' | ||
| ) | ||
| handler = mock.MagicMock( | ||
| request=request, | ||
| get_status=mock.Mock(return_value=500) | ||
| ) | ||
| logger = mock.MagicMock() | ||
| log.log_request(handler, log=logger, log_json=True) | ||
| # Since the status was 500 there should be two calls to log.error, | ||
| # one with the request headers and another with the other request | ||
| # parameters. | ||
| self.assertEqual(2, logger.error.call_count) | ||
| logger.error.assert_has_calls([ | ||
| mock.call("", extra=dict(props=dict(headers))), | ||
| mock.call("", extra=dict(props={ | ||
| 'status': handler.get_status(), | ||
| 'method': request.method, | ||
| 'ip': request.remote_ip, | ||
| 'uri': request.uri, | ||
| 'request_time': 1000.0, | ||
| 'referer': headers['Referer'] | ||
| })) | ||
| ]) | ||
| mock_prometheus.assert_called_once_with(handler) |
32 changes: 32 additions & 0 deletionsnotebook/tests/test_notebookapp.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletionssetup.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.