oslocontext(1)
| OSLOCONTEXT(1) | oslo.context | OSLOCONTEXT(1) |
NAME
oslocontext - oslo.context 5.7.1
The Oslo context library has helpers to maintain useful information about a request context. The request context is usually populated in the WSGI pipeline and used by various modules such as logging.
- License: Apache License, Version 2.0
- Documentation: https://docs.openstack.org/oslo.context/latest/
- Source: https://opendev.org/openstack/oslo.context
- Bugs: https://bugs.launchpad.net/oslo.context
- Release notes: https://docs.openstack.org/releasenotes/oslo.context/
TEAM AND REPOSITORY TAGS
Latest VersionDownloads.SH CONTENTS
Installation
At the command line:
$ pip install oslo.context
Using oslo.context
Usage
oslo.context is used in conjunction with oslo.log to provide context aware log records when specifying a RequestContext object.
This code example demonstrates two INFO log records with varying output format due to the use of RequestContext.
from oslo_config import cfg
from oslo_context import context
from oslo_log import log as logging
CONF = cfg.CONF
DOMAIN = "demo"
logging.register_options(CONF)
logging.setup(CONF, DOMAIN)
LOG = logging.getLogger(__name__)
LOG.info("Message without context")
context.RequestContext()
LOG.info("Message with context")
Source: usage_simple.py
Example Logging Output:
2016-01-20 21:56:29.283 8428 INFO __main__ [-] Message without context 2016-01-20 21:56:29.284 8428 INFO __main__ [req-929d23e9-f50e-46ae-a8a7-02bc8c3fd2c8 - - - - -] Message with context
The format of these log records are defined by the logging_default_format_string and logging_context_format_string configuration options respectively. The logging_user_identity_format option also provides further context aware definition flexibility.
Context Variables
The oslo.context variables used in the logging_context_format_string and logging_user_identity_format configuration options include:
- global_request_id - A request id (e.g. req-9f2c484a-b504-4fd9-b44c-4357544cca50) which may have been sent in from another service to indicate this is part of a chain of requests.
- request_id - A request id (e.g. req-9f2c484a-b504-4fd9-b44c-4357544cca50)
- user - A user id (e.g. e5bc7033e6b7473c9fe8ee1bd4df79a3)
- tenant - A tenant/project id (e.g. 79e338475db84f7c91ee4e86b79b34c1)
- domain - A domain id
- user_domain - A user domain id
- project_domain - A project domain id
This code example demonstrates defining a context with specific attributes that are presented in the output log record.
from oslo_config import cfg
from oslo_context import context
from oslo_log import log as logging
CONF = cfg.CONF
DOMAIN = "demo"
logging.register_options(CONF)
logging.setup(CONF, DOMAIN)
LOG = logging.getLogger(__name__)
LOG.info("Message without context")
# ids in Openstack are 32 characters long
# For readability a shorter id value is used
context.RequestContext(user='6ce90b4d',
tenant='d6134462',
project_domain='a6b9360e')
LOG.info("Message with context")
Source: usage.py
Example Logging Output:
2016-01-21 17:30:50.263 12201 INFO __main__ [-] Message without context 2016-01-21 17:30:50.264 12201 INFO __main__ [req-e591e881-36c3-4627-a5d8-54df200168ef 6ce90b4d d6134462 - - a6b9360e] Message with context
A context object can also be passed as an argument to any logging level message.
context = context.RequestContext(user='ace90b4d',
tenant='b6134462',
project_domain='c6b9360e') LOG.info("Message with passed context", context=context)
Example Logging Output:
2016-01-21 22:43:55.621 17295 INFO __main__ [req-ac2d4a3a-ff3c-4c2b-97a0-2b76b33d9e72 ace90b4d b6134462 - - c6b9360e] Message with passed context
NOTE:
Project Specific Variables
Individual projects can also subclass RequestContext to provide additional attributes that can be using with oslo.log. The Nova RequestContext class for example provides additional variables including user_name and project_name.
This can for example enable the defining of logging_user_identity_format = %(user_name)s %(project_name)s which would produce a log record containing a context portion using names instead of ids such as [req-e4b9a194-a9b1-4829-b7d0-35226fc101fc admin demo]
This following code example shows how a modified logging_user_identity_format configuration alters the context portion of the log record.
from oslo_config import cfg
from oslo_context import context
from oslo_log import log as logging
CONF = cfg.CONF
DOMAIN = "demo"
logging.register_options(CONF)
CONF.logging_user_identity_format = "%(user)s/%(tenant)s@%(project_domain)s"
logging.setup(CONF, DOMAIN)
LOG = logging.getLogger(__name__)
LOG.info("Message without context")
# ids in Openstack are 32 characters long
# For readability a shorter id value is used
context.RequestContext(request_id='req-abc',
user='6ce90b4d',
tenant='d6134462',
project_domain='a6b9360e')
LOG.info("Message with context")
Source: usage_user_identity.py
Example Logging Output:
2016-01-21 20:56:43.964 14816 INFO __main__ [-] Message without context 2016-01-21 20:56:43.965 14816 INFO __main__ [req-abc 6ce90b4d/d6134462@a6b9360e] Message with context
Examples
These files can be found in the doc/source/examples directory of the git source of this project. They can also be found at the online git repository of this project.
usage_simple.py
#!/usr/bin/env python3 # # Copyright (c) 2015 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """A simple usage example of Oslo Context This example requires the following modules to be installed. $ pip install oslo.context oslo.log More information can be found at:
https://docs.openstack.org/oslo.context/latest/user/usage.html """ from oslo_config import cfg from oslo_context import context from oslo_log import log as logging CONF = cfg.CONF DOMAIN = "demo" logging.register_options(CONF) logging.setup(CONF, DOMAIN) LOG = logging.getLogger(__name__) LOG.info("Message without context") context.RequestContext() LOG.info("Message with context")
usage.py
#!/usr/bin/env python3 # # Copyright (c) 2015 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """A representative usage example of Oslo Context This example requires the following modules to be installed. $ pip install oslo.context oslo.log More information can be found at:
https://docs.openstack.org/oslo.context/latest/user/usage.html """ from oslo_config import cfg from oslo_context import context from oslo_log import log as logging CONF = cfg.CONF DOMAIN = "demo" logging.register_options(CONF) logging.setup(CONF, DOMAIN) LOG = logging.getLogger(__name__) LOG.info("Message without context") # ids in Openstack are 32 characters long # For readability a shorter id value is used context.RequestContext(user='6ce90b4d',
tenant='d6134462',
project_domain='a6b9360e') LOG.info("Message with context") context = context.RequestContext(user='ace90b4d',
tenant='b6134462',
project_domain='c6b9360e') LOG.info("Message with passed context", context=context)
usage_user_identity.py
#!/usr/bin/env python3 # # Copyright (c) 2015 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """A usage example of Oslo Context with user_identity This example requires the following modules to be installed. $ pip install oslo.context oslo.log More information can be found at:
https://docs.openstack.org/oslo.context/latest/user/index.html """ from oslo_config import cfg from oslo_context import context from oslo_log import log as logging CONF = cfg.CONF DOMAIN = "demo" logging.register_options(CONF) CONF.logging_user_identity_format = "%(user)s/%(tenant)s@%(project_domain)s" logging.setup(CONF, DOMAIN) LOG = logging.getLogger(__name__) LOG.info("Message without context") # ids in Openstack are 32 characters long # For readability a shorter id value is used context.RequestContext(request_id='req-abc',
user='6ce90b4d',
tenant='d6134462',
project_domain='a6b9360e') LOG.info("Message with context")
CHANGES
5.7.1
- Skip installation to speed up pep8
- reno: Update master for unmaintained/2023.1
5.7.0
- Stop setting deprecated fields in redacted_copy
- Add note about requirements lower bounds
- Run pyupgrade to clean up Python 2 syntaxes
- Remove Python 3.8 support
- Fix outdated tox minversion
- Declare Python 3.12 support
- Drop SETUPTOOLS_USE_DISTUTILS
- Update master for stable/2024.2
5.6.0
- reno: Update master for unmaintained/zed
- Remove old excludes
- pre-commit: Remove outdated comment
- Update master for stable/2024.1
- reno: Update master for unmaintained/xena
- reno: Update master for unmaintained/wallaby
- reno: Update master for unmaintained/victoria
5.5.0
- •
- Add is_admin to redacted context
5.4.0
- reno: Update master for unmaintained/yoga
- tox: Drop envdir
- Bump hacking
- Update python classifier in setup.cfg
5.3.0
- pre-commit: Integrate bandit, mypy
- pre-commit: Bump dependencies
- Add method for getting redacted copy of context
- Update master for stable/2023.2
- Bump bandit
5.2.0
- Revert "Moves supported python runtimes from version 3.8 to 3.10"
- Moves supported python runtimes from version 3.8 to 3.10
- Update master for stable/2023.1
5.1.1
- •
- Fix the docs job
5.1.0
- Add Python3 antelope unit tests
- Update master for stable/zed
- Cleanup py27 support
5.0.0
- Drop python3.6/3.7 support in testing runtime
- Remove unnecessary unicode prefixes
- Add Python3 zed unit tests
- Update master for stable/yoga
4.1.0
- •
- Integrate mypy
4.0.0
- Don't test with setuptools local distutils
- Remove the deprecated argument tenant from RequestContext
3.4.0
- Add Python3 yoga unit tests
- Update master for stable/xena
- Fix context from_dict() for system_scope
3.3.1
3.3.0
- setup.cfg: Replace dashes with underscores
- Ussuri+ is python3 only and update python to python3
- Fix formatting of release list
- Move flake8 as a pre-commit local target
- Add Python3 xena unit tests
- Update master for stable/wallaby
- Remove lower-constraints remnants
- Drop use of deprecated collections classes
3.2.0
- Switch to collections.abc.MutableMapping
- Dropping lower constraints testing
- Use TOX_CONSTRAINTS_FILE
- Use py3 as the default runtime for tox
- Add Python3 wallaby unit tests
- Update master for stable/victoria
- Adding pre-commit
3.1.1
- Bump bandit version
- drop mock from lower-constraints
- Fix pygments style
3.1.0
- Remove translation sections from setup.cfg
- Fix hacking min version to 3.0.1
- Switch to newer openstackdocstheme and reno versions
- Remove the unused coding style modules
- Align contributing doc with oslo's policy
- Bump default tox env from py37 to py38
- Add py38 package metadata
- Add release notes links to doc index
- Add Python3 victoria unit tests
- Update master for stable/ussuri
3.0.2
- •
- Don't build universal wheel
3.0.1
- Update hacking for Python3
- Filter out auth_token_info from logging values
- trivial: Cleanup tox.ini
- remove outdated header
- reword releasenote for py27 support dropping
3.0.0
- Drop python 2.7 support and testing
- tox: Trivial cleanup
- tox: Trivial cleanup
- Bump the openstackdocstheme extension to 1.20
- gitignore: Hide reno cache files
- tox: Stop using 'python setup.py test'
- Switch to Ussuri jobs
- tox: Keeping going with docs
- Switch to Ussuri jobs
- Update the constraints url
- Update master for stable/train
2.23.0
- Add Python 3 Train unit tests
- Cap Bandit below 1.6.0 and update Sphinx requirement
- Replace git.openstack.org URLs with opendev.org URLs
- OpenDev Migration Patch
- Dropping the py35 testing
- Update master for stable/stein
2.22.1
- add python 3.7 unit test job
- Update hacking version
- Use template for lower-constraints
- Update mailinglist from dev to discuss
2.22.0
- Implement domain-scope for context objects
- Clean up .gitignore references to personal tools
- Always build universal wheels
- add lib-forward-testing-python3 test job
- add python 3.6 unit test job
- import zuul job settings from project-config
- import zuul job settings from project-config
- Update reno for stable/rocky
- Switch to stestr
- Add release notes link to README
- fix tox python3 overrides
2.21.0
- Implement system-scope
- Remove stale pip-missing-reqs tox test
- Trivial: Update pypi url to new url
- Switch pep8 job to python 3
- add lower-constraints job
- pypy not checked at gate
- Updated from global requirements
- Update links in README
- Add -W for document build
- Update reno for stable/queens
- Updated from global requirements
- Updated from global requirements
- Updated from global requirements
- Updated from global requirements
2.20.0
- Updated from global requirements
- Follow the new PTI for document build
- Remove -U from pip install
- Avoid tox_install.sh for constraints support
- add bandit to pep8 job
- Remove setting of version/release from releasenotes
2.19.3
- •
- Ouput a placeholder instead of the auth_token
2.19.2
- •
- Make from_dict extensible
2.19.1
- Output 'project' key in context's to_dict function
- Rename deprecated context params
2.19.0
- •
- Updated from global requirements
2.18.1
- Update the documentation link for doc migration
- Revert "Postpone deprecation warnings to Pike"
2.18.0
- Updated from global requirements
- Remove use of positional decorator
- Update reno for stable/pike
- Updated from global requirements
2.17.0
- Fix URLs according to document migration
- Cleanup document formatting
- rearrange the documentation to fit into the new standard layout
2.16.0
- Switch from oslosphinx to openstackdocstheme
- Updated from global requirements
2.15.0
- Optimize the link address
- Remove pbr warnerrors in favor of sphinx check
- Updated from global requirements
2.14.0
- Provide unified calling interface for global_id
- Add global_request_id to context
- Updated from global requirements
- Updated from global requirements
- Updated from global requirements
2.13.0
- Updated from global requirements
- [Fix gate]Update test requirement
- Updated from global requirements
- pbr.version.VersionInfo needs package name (oslo.xyz and not oslo_xyz)
- Postpone deprecation warnings to Pike
- Update reno for stable/ocata
2.12.0
- Updated from global requirements
- Remove references to Python 3.4
- Add Constraints support
- Show team and repo badges on README
- Add the service token details to context
- Reformat the Context.__init__ arguments
- Move existing attributes to _id suffixed attributes
2.11.0
- Updated from global requirements
- Revert "Fix X-User and X-Tenant deprecated headers in from_environ"
- Updated from global requirements
- Updated from global requirements
- Changed the home-page link
2.10.0
- Enable release notes translation
- Updated from global requirements
- Provide a way to deprecate policy values
- Update reno for stable/newton
- Fix typos
- Fix X-User and X-Tenant deprecated headers in from_environ
2.9.0
- •
- Updated from global requirements
2.8.0
- Delete H803 in flake8 ignore list
- Fix parameters of assertEqual are misplaced
- Manually specify from_dict parameters
2.7.0
- Add Python 3.5 classifier and venv
- Emit deprecation warnings when positional args passed
2.6.0
- Allow deprecated X-Tenant-Name in from_environ
- Handle openstack.request_id in from_environ
- Add is_admin_project to context
- Updated from global requirements
2.5.0
- Add reno for releasenotes management
- Add oslo.context name attributes matching ids
2.4.0
- Trivial: ignore openstack/common in flake8 exclude list
- Strip roles in from_environ
- Allow deprecated headers in from_environ
2.3.0
- Drop babel as requirement since its not used
- Updated from global requirements
- Ensure to_dict() supports unicode
2.2.0
- Standardize an oslo.policy credentials dictionary
- Revert "Add common oslo.log format parameters"
- Add roles to context
2.1.0
- Agnostic approach to construct context from_dict
- Add common oslo.log format parameters
2.0.0
- Improve Context docs with example syntax
- Define method for oslo.log context parameters
- Add additional unit tests
- Fix request_id type on Python 3: use text (Unicode)
- Updated from global requirements
- Provide a helper to load a context from environment
1.0.1
- Revert "Add properties for id attributes"
- Add properties for id attributes
- Trival: Remove 'MANIFEST.in'
1.0.0
- Updated from global requirements
- Remove python 2.6 classifier
- Remove python 2.6 and cleanup tox.ini
0.9.0
- •
- Remove reference to undefined attributes
0.8.0
- •
- Fix coverage configuration and execution
0.7.0
- Add shields.io version/downloads links/badges into README.rst
- Change ignore-errors to ignore_errors
- Updated from global requirements
0.6.0
- Updated from global requirements
- Updated from global requirements
- Updated from global requirements
0.5.0
- Updated from global requirements
- Updated from global requirements
- Add tox target to find missing requirements
- Updated from global requirements
- Updated from global requirements
0.4.0
- Remove support for Python 3.3
- Do not sync run_cross_tests.sh
- Updated from global requirements
0.3.0
- Uncap library requirements for liberty
- Standardize setup.cfg summary for oslo libs
- Update to latest hacking
- Updated from global requirements
- fix bug tracker link
0.2.0
- ensure we reset contexts when fixture is used
- Activate pep8 check that _ is imported
0.1.0
- Workflow documentation is now in infra-manual
- Documentation cleanup
- Add ClearRequestContext fixture
- Cache the current context for the thread
- Add docstring to get_admin_context()
- Change instance_uuid to resource_uuid
- Better information in the README
- Generate better documentation for the module
- Move out of the oslo namespace package
- get test to actually run
- fix links and requirements to latest versions
- Make the unit test run properly - fix import
- exported from oslo-incubator by graduate.sh
- Add a RequestContext.from_dict method
- Use oslotest instead of common test module
- Python 3: enable tests/unit/middleware/test_request_id.py
- Add model_query() to db.sqlalchemy.utils module
- Adding domain to context and log
- Remove vim header
- Remove uuidutils imports in oslo modules
- Revert "Removes generate_uuid from uuidutils"
- Removes generate_uuid from uuidutils
- Adding instance_uuid to context and log
- Replace using tests.utils with openstack.common.test
- Fix bad default for show_deleted
- Enable hacking H404 test
- Replaces the standard uuid with common in the context module
- Fix Copyright Headers - Rename LLC to Foundation
- Fix inconsistency with auth_tok/auth_token
- Replace direct use of testtools BaseTestCase
- Use testtools as test base class
- Move get_context_from_function_and_args() to context.py
- Added dictify() and uuids to the common request context
- add context 'tests'
- make the skeleton project a template
- reog from import merge
- Add some more generic middleware, request context, utils, and versioning. Add basic template for server binary
- Initial skeleton project
Contributing
If you would like to contribute to the development of oslo's libraries, first you must take a look to this page:
If you would like to contribute to the development of OpenStack, you must follow the steps in this page: https://docs.openstack.org/infra/manual/developers.html
Once those steps have been completed, changes to OpenStack should be submitted for review via the Gerrit tool, following the workflow documented at: https://docs.openstack.org/infra/manual/developers.html#development-workflow
Pull requests submitted through GitHub will be ignored.
Bugs should be filed on Launchpad, not GitHub: https://bugs.launchpad.net/oslo.context
CODE DOCUMENTATION
API reference
The oslo_context.context Module
Base class for holding contextual information of a request
This class has several uses:
- Used for storing security information in a web request.
- Used for passing contextual details to oslo.log.
Projects should subclass this class if they wish to enhance the request context or provide additional information in their specific WSGI pipeline or logging context.
- class oslo_context.context.RequestContext(auth_token: str | None = None, user_id: str | None = None, project_id: str | None = None, domain_id: str | None = None, user_domain_id: str | None = None, project_domain_id: str | None = None, is_admin: bool = False, read_only: bool = False, show_deleted: bool = False, request_id: str | None = None, resource_uuid: str | None = None, overwrite: bool = True, roles: List[str] | None = None, user_name: str | None = None, project_name: str | None = None, domain_name: str | None = None, user_domain_name: str | None = None, project_domain_name: str | None = None, is_admin_project: bool = True, service_token: str | None = None, service_user_id: str | None = None, service_user_name: str | None = None, service_user_domain_id: str | None = None, service_user_domain_name: str | None = None, service_project_id: str | None = None, service_project_name: str | None = None, service_project_domain_id: str | None = None, service_project_domain_name: str | None = None, service_roles: List[str] | None = None, global_request_id: str | None = None, system_scope: str | None = None)
- Bases: object
Helper class to represent useful information about a request context.
Stores information about the security context under which the user accesses the system, as well as additional request information.
- FROM_DICT_EXTRA_KEYS: List[str] = []
- property domain: Any
- property domain_id: Any
- classmethod from_dict(values: Dict[str, Any], **kwargs: Any) -> RequestContext
- Construct a context object from a provided dictionary.
- classmethod from_environ(environ: Dict[str, Any], **kwargs: Any) -> RequestContext
- Load a context object from a request environment.
If keyword arguments are provided then they override the values in the request environment.
- Parameters
- environ (dict) -- The environment dictionary associated with a request.
- get_logging_values() -> Dict[str, Any]
- Return a dictionary of logging specific context attributes.
- property global_id: str
- Return a sensible value for global_id to pass on.
When we want to make a call with to another service, it's important that we try to use global_request_id if available, and fall back to the locally generated request_id if not.
- property project_domain: Any
- property project_domain_id: Any
- property project_id: Any
- redacted_copy(**kwargs: Any) -> RequestContext
- Return a copy of the context with sensitive fields redacted.
This is useful for creating a context that can be safely logged.
- Returns
- A copy of the context with sensitive fields redacted.
- to_dict() -> Dict[str, Any]
- Return a dictionary of context attributes.
- to_policy_values() -> _DeprecatedPolicyValues
- A dictionary of context attributes to enforce policy with.
oslo.policy enforcement requires a dictionary of attributes representing the current logged in user on which it applies policy enforcement. This dictionary defines a standard list of attributes that should be available for enforcement across services.
It is expected that services will often have to override this method with either deprecated values or additional attributes used by that service specific policy.
- update_store() -> None
- Store the context in the current thread.
- property user: Any
- property user_domain: Any
- property user_domain_id: Any
- property user_id: Any
- user_idt_format = '{user} {project_id} {domain} {user_domain} {p_domain}'
- oslo_context.context.generate_request_id() -> str
- Generate a unique request id.
- oslo_context.context.get_admin_context(show_deleted: bool = False) -> RequestContext
- Create an administrator context.
- oslo_context.context.get_context_from_function_and_args(function: Callable, args: List[Any], kwargs: Dict[str, Any]) -> RequestContext | None
- Find an arg of type RequestContext and return it.
This is useful in a couple of decorators where we don't know much about the function we're wrapping.
- oslo_context.context.get_current() -> RequestContext | None
- Return this thread's current context
If no context is set, returns None
- oslo_context.context.is_user_context(context: RequestContext) -> bool
- Indicates if the request context is a normal user.
The oslo_context.fixture Module
- class oslo_context.fixture.ClearRequestContext
- Bases: Fixture
Clears any cached RequestContext
This resets RequestContext at the beginning and end of tests that use this fixture to ensure that we have a clean slate for running tests, and that we leave a clean slate for other tests that might run later in the same process.
- setUp() -> None
- Prepare the Fixture for use.
This should not be overridden. Concrete fixtures should implement _setUp. Overriding of setUp is still supported, just not recommended.
After setUp has completed, the fixture will have one or more attributes which can be used (these depend totally on the concrete subclass).
- Raises
- MultipleExceptions if _setUp fails. The last exception captured within the MultipleExceptions will be a SetupError exception.
- Returns
- None.
- Changed in 1.3
- The recommendation to override setUp has been reversed - before 1.3, setUp() should be overridden, now it should not be.
- Changed in 1.3.1
- BaseException is now caught, and only subclasses of Exception are wrapped in MultipleExceptions.
RELEASE NOTES
Read also the oslo.context Release Notes.
INDICES AND TABLES
- Index
- Module Index
- Search Page
AUTHOR
Author name not set
COPYRIGHT
2025, OpenStack Foundation
| April 2, 2025 | 5.7.1 |
