index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
|---|---|---|---|---|---|
710,391
|
json_logging.framework_base
|
config
|
configuration logic
:param app:
|
def config(self, app, exclude_url_patterns=None):
"""
configuration logic
:param app:
"""
raise NotImplementedError
|
(self, app, exclude_url_patterns=None)
|
710,392
|
json_logging.framework_base
|
get_request_logger
|
get the current logger that is used to logger the request instrumentation information
|
def get_request_logger(self):
"""
get the current logger that is used to logger the request instrumentation information
"""
return self.request_logger
|
(self)
|
710,393
|
json_logging
|
BaseJSONFormatter
|
Base class for JSON formatters
|
class BaseJSONFormatter(logging.Formatter):
"""
Base class for JSON formatters
"""
base_object_common = {}
def __init__(self, *args, **kw):
super(BaseJSONFormatter, self).__init__(*args, **kw)
if COMPONENT_ID and COMPONENT_ID != EMPTY_VALUE:
self.base_object_common["component_id"] = COMPONENT_ID
if COMPONENT_NAME and COMPONENT_NAME != EMPTY_VALUE:
self.base_object_common["component_name"] = COMPONENT_NAME
if COMPONENT_INSTANCE_INDEX and COMPONENT_INSTANCE_INDEX != EMPTY_VALUE:
self.base_object_common["component_instance_idx"] = COMPONENT_INSTANCE_INDEX
def format(self, record):
log_object = self._format_log_object(record, request_util=_request_util)
return JSON_SERIALIZER(log_object)
def _format_log_object(self, record, request_util):
utcnow = datetime.utcnow()
base_obj = {
"written_at": util.iso_time_format(utcnow),
"written_ts": util.epoch_nano_second(utcnow),
}
base_obj.update(self.base_object_common)
return base_obj
|
(*args, **kw)
|
710,394
|
json_logging
|
__init__
| null |
def __init__(self, *args, **kw):
super(BaseJSONFormatter, self).__init__(*args, **kw)
if COMPONENT_ID and COMPONENT_ID != EMPTY_VALUE:
self.base_object_common["component_id"] = COMPONENT_ID
if COMPONENT_NAME and COMPONENT_NAME != EMPTY_VALUE:
self.base_object_common["component_name"] = COMPONENT_NAME
if COMPONENT_INSTANCE_INDEX and COMPONENT_INSTANCE_INDEX != EMPTY_VALUE:
self.base_object_common["component_instance_idx"] = COMPONENT_INSTANCE_INDEX
|
(self, *args, **kw)
|
710,395
|
json_logging
|
_format_log_object
| null |
def _format_log_object(self, record, request_util):
utcnow = datetime.utcnow()
base_obj = {
"written_at": util.iso_time_format(utcnow),
"written_ts": util.epoch_nano_second(utcnow),
}
base_obj.update(self.base_object_common)
return base_obj
|
(self, record, request_util)
|
710,396
|
json_logging
|
format
| null |
def format(self, record):
log_object = self._format_log_object(record, request_util=_request_util)
return JSON_SERIALIZER(log_object)
|
(self, record)
|
710,403
|
json_logging.framework_base
|
FrameworkConfigurator
|
Class to perform logging configuration for given framework as needed, like disable built in request logging and other utils logging
|
class FrameworkConfigurator:
"""
Class to perform logging configuration for given framework as needed, like disable built in request logging and other utils logging
"""
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls)
return cls._instance
def config(self):
"""
app logging configuration logic
"""
raise NotImplementedError
|
(*args, **kw)
|
710,404
|
json_logging.framework_base
|
__new__
| null |
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls)
return cls._instance
|
(cls, *args, **kw)
|
710,405
|
json_logging.framework_base
|
config
|
app logging configuration logic
|
def config(self):
"""
app logging configuration logic
"""
raise NotImplementedError
|
(self)
|
710,406
|
json_logging
|
JSONLogFormatter
|
Formatter for non-web application log
|
class JSONLogFormatter(BaseJSONFormatter):
"""
Formatter for non-web application log
"""
def get_exc_fields(self, record):
if record.exc_info:
exc_info = self.format_exception(record.exc_info)
else:
exc_info = record.exc_text
return {
'exc_info': exc_info,
'filename': record.filename,
}
@classmethod
def format_exception(cls, exc_info):
return ''.join(traceback.format_exception(*exc_info)) if exc_info else ''
def _format_log_object(self, record, request_util):
json_log_object = super(JSONLogFormatter, self)._format_log_object(record, request_util)
json_log_object.update({
"msg": _sanitize_log_msg(record),
"type": "log",
"logger": record.name,
"thread": record.threadName,
"level": record.levelname,
"module": record.module,
"line_no": record.lineno,
})
if hasattr(record, 'props'):
json_log_object.update(record.props)
if record.exc_info or record.exc_text:
json_log_object.update(self.get_exc_fields(record))
return json_log_object
|
(*args, **kw)
|
710,408
|
json_logging
|
_format_log_object
| null |
def _format_log_object(self, record, request_util):
json_log_object = super(JSONLogFormatter, self)._format_log_object(record, request_util)
json_log_object.update({
"msg": _sanitize_log_msg(record),
"type": "log",
"logger": record.name,
"thread": record.threadName,
"level": record.levelname,
"module": record.module,
"line_no": record.lineno,
})
if hasattr(record, 'props'):
json_log_object.update(record.props)
if record.exc_info or record.exc_text:
json_log_object.update(self.get_exc_fields(record))
return json_log_object
|
(self, record, request_util)
|
710,414
|
json_logging
|
get_exc_fields
| null |
def get_exc_fields(self, record):
if record.exc_info:
exc_info = self.format_exception(record.exc_info)
else:
exc_info = record.exc_text
return {
'exc_info': exc_info,
'filename': record.filename,
}
|
(self, record)
|
710,416
|
json_logging
|
JSONLogWebFormatter
|
Formatter for web application log
|
class JSONLogWebFormatter(JSONLogFormatter):
"""
Formatter for web application log
"""
def _format_log_object(self, record, request_util):
json_log_object = super(JSONLogWebFormatter, self)._format_log_object(record, request_util)
json_log_object.update({
"correlation_id": request_util.get_correlation_id(within_formatter=True),
})
return json_log_object
|
(*args, **kw)
|
710,418
|
json_logging
|
_format_log_object
| null |
def _format_log_object(self, record, request_util):
json_log_object = super(JSONLogWebFormatter, self)._format_log_object(record, request_util)
json_log_object.update({
"correlation_id": request_util.get_correlation_id(within_formatter=True),
})
return json_log_object
|
(self, record, request_util)
|
710,426
|
json_logging
|
JSONRequestLogFormatter
|
Formatter for HTTP request instrumentation logging
|
class JSONRequestLogFormatter(BaseJSONFormatter):
"""
Formatter for HTTP request instrumentation logging
"""
def _format_log_object(self, record, request_util):
json_log_object = super(JSONRequestLogFormatter, self)._format_log_object(record, request_util)
request = record.request_info.request
request_adapter = request_util.request_adapter
length = request_adapter.get_content_length(request)
json_log_object.update({
"type": "request",
"correlation_id": request_util.get_correlation_id(request),
"remote_user": request_adapter.get_remote_user(request),
"request": request_adapter.get_path(request),
"referer": request_adapter.get_http_header(request, 'referer', EMPTY_VALUE),
"x_forwarded_for": request_adapter.get_http_header(request, 'x-forwarded-for', EMPTY_VALUE),
"protocol": request_adapter.get_protocol(request),
"method": request_adapter.get_method(request),
"remote_ip": request_adapter.get_remote_ip(request),
"request_size_b": util.parse_int(length, -1),
"remote_host": request_adapter.get_remote_ip(request),
"remote_port": request_adapter.get_remote_port(request),
"request_received_at": record.request_info.request_received_at,
"response_time_ms": record.request_info.response_time_ms,
"response_status": record.request_info.response_status,
"response_size_b": record.request_info.response_size_b,
"response_content_type": record.request_info.response_content_type,
"response_sent_at": record.request_info.response_sent_at
})
return json_log_object
|
(*args, **kw)
|
710,428
|
json_logging
|
_format_log_object
| null |
def _format_log_object(self, record, request_util):
json_log_object = super(JSONRequestLogFormatter, self)._format_log_object(record, request_util)
request = record.request_info.request
request_adapter = request_util.request_adapter
length = request_adapter.get_content_length(request)
json_log_object.update({
"type": "request",
"correlation_id": request_util.get_correlation_id(request),
"remote_user": request_adapter.get_remote_user(request),
"request": request_adapter.get_path(request),
"referer": request_adapter.get_http_header(request, 'referer', EMPTY_VALUE),
"x_forwarded_for": request_adapter.get_http_header(request, 'x-forwarded-for', EMPTY_VALUE),
"protocol": request_adapter.get_protocol(request),
"method": request_adapter.get_method(request),
"remote_ip": request_adapter.get_remote_ip(request),
"request_size_b": util.parse_int(length, -1),
"remote_host": request_adapter.get_remote_ip(request),
"remote_port": request_adapter.get_remote_port(request),
"request_received_at": record.request_info.request_received_at,
"response_time_ms": record.request_info.response_time_ms,
"response_status": record.request_info.response_status,
"response_size_b": record.request_info.response_size_b,
"response_content_type": record.request_info.response_content_type,
"response_sent_at": record.request_info.response_sent_at
})
return json_log_object
|
(self, record, request_util)
|
710,435
|
json_logging
|
<lambda>
| null |
JSON_SERIALIZER = lambda log: json.dumps(log, ensure_ascii=False)
|
(log)
|
710,436
|
json_logging.framework_base
|
RequestAdapter
|
Helper class help to extract logging-relevant information from HTTP request object
|
class RequestAdapter:
"""
Helper class help to extract logging-relevant information from HTTP request object
"""
def __new__(cls, *arg, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls)
return cls._instance
@staticmethod
def support_global_request_object():
"""
whether current framework supports global request object like Flask
"""
raise NotImplementedError
@staticmethod
def get_current_request():
"""
get current request, should only implement for framework that support global request object
"""
raise NotImplementedError
@staticmethod
def get_request_class_type():
"""
class type of request object, only need to specify in case the framework dont support global request object
"""
raise NotImplementedError
def get_http_header(self, request, header_name, default=None):
"""
get HTTP header value given it value name
:param request: request object
:param header_name: name of header
:param default: default value if header value is not present
:return:
"""
raise NotImplementedError
def get_remote_user(self, request):
"""
:param request: request object
"""
raise NotImplementedError
def set_correlation_id(self, request, value):
"""
We can safely assume that request is valid request object.\n
Set correlation to request context. e.g Flask.g in Flask
Made sure that we can access it later from get_correlation_id_in_request_context given the same request.
:param value: correlation id string
:param request: request object
"""
raise NotImplementedError
def get_correlation_id_in_request_context(self, request):
"""
We can safely assume that request is valid request object.
:param request: request object
"""
raise NotImplementedError
def get_protocol(self, request):
"""
We can safely assume that request is valid request object.\n
Gets the request protocol (e.g. HTTP/1.1).
:return: The request protocol or '-' if it cannot be determined
"""
raise NotImplementedError
def get_path(self, request):
"""
We can safely assume that request is valid request object.\n
Gets the request path.
:return: the request path (e.g. /index.html)
"""
raise NotImplementedError
def get_content_length(self, request):
"""
We can safely assume that request is valid request object.\n
The content length of the request.
:return: the content length of the request or '-' if it cannot be determined
"""
raise NotImplementedError
def get_method(self, request):
"""
We can safely assume that request is valid request object.\n
Gets the request method (e.g. GET, POST, etc.).
:return: The request method or '-' if it cannot be determined
"""
raise NotImplementedError
def get_remote_ip(self, request):
"""
We can safely assume that request is valid request object.\n
Gets the remote ip of the request initiator.
:return: An ip address or '-' if it cannot be determined
"""
raise NotImplementedError
def get_remote_port(self, request):
"""
We can safely assume that request is valid request object.\n
Gets the remote port of the request initiator.
:return: A port or '-' if it cannot be determined
"""
raise NotImplementedError
|
(*arg, **kwargs)
|
710,437
|
json_logging.framework_base
|
__new__
| null |
def __new__(cls, *arg, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls)
return cls._instance
|
(cls, *arg, **kwargs)
|
710,438
|
json_logging.framework_base
|
get_content_length
|
We can safely assume that request is valid request object.
The content length of the request.
:return: the content length of the request or '-' if it cannot be determined
|
def get_content_length(self, request):
"""
We can safely assume that request is valid request object.\n
The content length of the request.
:return: the content length of the request or '-' if it cannot be determined
"""
raise NotImplementedError
|
(self, request)
|
710,439
|
json_logging.framework_base
|
get_correlation_id_in_request_context
|
We can safely assume that request is valid request object.
:param request: request object
|
def get_correlation_id_in_request_context(self, request):
"""
We can safely assume that request is valid request object.
:param request: request object
"""
raise NotImplementedError
|
(self, request)
|
710,440
|
json_logging.framework_base
|
get_current_request
|
get current request, should only implement for framework that support global request object
|
@staticmethod
def get_current_request():
"""
get current request, should only implement for framework that support global request object
"""
raise NotImplementedError
|
()
|
710,441
|
json_logging.framework_base
|
get_http_header
|
get HTTP header value given it value name
:param request: request object
:param header_name: name of header
:param default: default value if header value is not present
:return:
|
def get_http_header(self, request, header_name, default=None):
"""
get HTTP header value given it value name
:param request: request object
:param header_name: name of header
:param default: default value if header value is not present
:return:
"""
raise NotImplementedError
|
(self, request, header_name, default=None)
|
710,442
|
json_logging.framework_base
|
get_method
|
We can safely assume that request is valid request object.
Gets the request method (e.g. GET, POST, etc.).
:return: The request method or '-' if it cannot be determined
|
def get_method(self, request):
"""
We can safely assume that request is valid request object.\n
Gets the request method (e.g. GET, POST, etc.).
:return: The request method or '-' if it cannot be determined
"""
raise NotImplementedError
|
(self, request)
|
710,443
|
json_logging.framework_base
|
get_path
|
We can safely assume that request is valid request object.
Gets the request path.
:return: the request path (e.g. /index.html)
|
def get_path(self, request):
"""
We can safely assume that request is valid request object.\n
Gets the request path.
:return: the request path (e.g. /index.html)
"""
raise NotImplementedError
|
(self, request)
|
710,444
|
json_logging.framework_base
|
get_protocol
|
We can safely assume that request is valid request object.
Gets the request protocol (e.g. HTTP/1.1).
:return: The request protocol or '-' if it cannot be determined
|
def get_protocol(self, request):
"""
We can safely assume that request is valid request object.\n
Gets the request protocol (e.g. HTTP/1.1).
:return: The request protocol or '-' if it cannot be determined
"""
raise NotImplementedError
|
(self, request)
|
710,445
|
json_logging.framework_base
|
get_remote_ip
|
We can safely assume that request is valid request object.
Gets the remote ip of the request initiator.
:return: An ip address or '-' if it cannot be determined
|
def get_remote_ip(self, request):
"""
We can safely assume that request is valid request object.\n
Gets the remote ip of the request initiator.
:return: An ip address or '-' if it cannot be determined
"""
raise NotImplementedError
|
(self, request)
|
710,446
|
json_logging.framework_base
|
get_remote_port
|
We can safely assume that request is valid request object.
Gets the remote port of the request initiator.
:return: A port or '-' if it cannot be determined
|
def get_remote_port(self, request):
"""
We can safely assume that request is valid request object.\n
Gets the remote port of the request initiator.
:return: A port or '-' if it cannot be determined
"""
raise NotImplementedError
|
(self, request)
|
710,447
|
json_logging.framework_base
|
get_remote_user
|
:param request: request object
|
def get_remote_user(self, request):
"""
:param request: request object
"""
raise NotImplementedError
|
(self, request)
|
710,448
|
json_logging.framework_base
|
get_request_class_type
|
class type of request object, only need to specify in case the framework dont support global request object
|
@staticmethod
def get_request_class_type():
"""
class type of request object, only need to specify in case the framework dont support global request object
"""
raise NotImplementedError
|
()
|
710,449
|
json_logging.framework_base
|
set_correlation_id
|
We can safely assume that request is valid request object.
Set correlation to request context. e.g Flask.g in Flask
Made sure that we can access it later from get_correlation_id_in_request_context given the same request.
:param value: correlation id string
:param request: request object
|
def set_correlation_id(self, request, value):
"""
We can safely assume that request is valid request object.\n
Set correlation to request context. e.g Flask.g in Flask
Made sure that we can access it later from get_correlation_id_in_request_context given the same request.
:param value: correlation id string
:param request: request object
"""
raise NotImplementedError
|
(self, request, value)
|
710,450
|
json_logging.framework_base
|
support_global_request_object
|
whether current framework supports global request object like Flask
|
@staticmethod
def support_global_request_object():
"""
whether current framework supports global request object like Flask
"""
raise NotImplementedError
|
()
|
710,451
|
json_logging
|
RequestInfo
|
class that keep HTTP request information for request instrumentation logging
|
class RequestInfo(dict):
"""
class that keep HTTP request information for request instrumentation logging
"""
def __init__(self, request, **kwargs):
super(RequestInfo, self).__init__(**kwargs)
utcnow = datetime.utcnow()
self.request_start = utcnow
self.request = request
self.request_received_at = util.iso_time_format(utcnow)
# noinspection PyAttributeOutsideInit
def update_response_status(self, response):
"""
update response information into this object, must be called before invoke request logging statement
:param response:
"""
response_adapter = _request_util.response_adapter
utcnow = datetime.utcnow()
time_delta = utcnow - self.request_start
self.response_time_ms = int(time_delta.total_seconds()) * 1000 + int(time_delta.microseconds / 1000)
self.response_status = response_adapter.get_status_code(response)
self.response_size_b = response_adapter.get_response_size(response)
self.response_content_type = response_adapter.get_content_type(response)
self.response_sent_at = util.iso_time_format(utcnow)
|
(request, **kwargs)
|
710,452
|
json_logging
|
__init__
| null |
def __init__(self, request, **kwargs):
super(RequestInfo, self).__init__(**kwargs)
utcnow = datetime.utcnow()
self.request_start = utcnow
self.request = request
self.request_received_at = util.iso_time_format(utcnow)
|
(self, request, **kwargs)
|
710,453
|
json_logging
|
update_response_status
|
update response information into this object, must be called before invoke request logging statement
:param response:
|
def update_response_status(self, response):
"""
update response information into this object, must be called before invoke request logging statement
:param response:
"""
response_adapter = _request_util.response_adapter
utcnow = datetime.utcnow()
time_delta = utcnow - self.request_start
self.response_time_ms = int(time_delta.total_seconds()) * 1000 + int(time_delta.microseconds / 1000)
self.response_status = response_adapter.get_status_code(response)
self.response_size_b = response_adapter.get_response_size(response)
self.response_content_type = response_adapter.get_content_type(response)
self.response_sent_at = util.iso_time_format(utcnow)
|
(self, response)
|
710,454
|
json_logging.framework_base
|
ResponseAdapter
|
Helper class help to extract logging-relevant information from HTTP response object
|
class ResponseAdapter:
"""
Helper class help to extract logging-relevant information from HTTP response object
"""
def __new__(cls, *arg, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls)
return cls._instance
def get_status_code(self, response):
"""
get response's integer status code
:param response: response object
"""
raise NotImplementedError
def get_response_size(self, response):
"""
get response's size in bytes
:param response: response object
"""
raise NotImplementedError
def get_content_type(self, response):
"""
get response's MIME/media type
:param response: response object
"""
raise NotImplementedError
|
(*arg, **kwargs)
|
710,456
|
json_logging.framework_base
|
get_content_type
|
get response's MIME/media type
:param response: response object
|
def get_content_type(self, response):
"""
get response's MIME/media type
:param response: response object
"""
raise NotImplementedError
|
(self, response)
|
710,457
|
json_logging.framework_base
|
get_response_size
|
get response's size in bytes
:param response: response object
|
def get_response_size(self, response):
"""
get response's size in bytes
:param response: response object
"""
raise NotImplementedError
|
(self, response)
|
710,458
|
json_logging.framework_base
|
get_status_code
|
get response's integer status code
:param response: response object
|
def get_status_code(self, response):
"""
get response's integer status code
:param response: response object
"""
raise NotImplementedError
|
(self, response)
|
710,459
|
json_logging.framework.sanic
|
SanicAppConfigurator
| null |
class SanicAppConfigurator(FrameworkConfigurator):
def config(self):
if not is_sanic_present():
raise RuntimeError("Sanic is not available in system runtime")
# from sanic.config import LOGGING
# noinspection PyPackageRequirements
from sanic.log import LOGGING_CONFIG_DEFAULTS
LOGGING_CONFIG_DEFAULTS["disable_existing_loggers"] = False
LOGGING_CONFIG_DEFAULTS["formatters"]["generic"][
"class"
] = "json_logging.JSONLogFormatter"
del LOGGING_CONFIG_DEFAULTS["formatters"]["generic"]["format"]
LOGGING_CONFIG_DEFAULTS["formatters"]["access"][
"class"
] = "json_logging.JSONLogFormatter"
del LOGGING_CONFIG_DEFAULTS["formatters"]["access"]["format"]
# logging.config.dictConfig(LOGGING_CONFIG_DEFAULTS)
|
(*args, **kw)
|
710,461
|
json_logging.framework.sanic
|
config
| null |
def config(self):
if not is_sanic_present():
raise RuntimeError("Sanic is not available in system runtime")
# from sanic.config import LOGGING
# noinspection PyPackageRequirements
from sanic.log import LOGGING_CONFIG_DEFAULTS
LOGGING_CONFIG_DEFAULTS["disable_existing_loggers"] = False
LOGGING_CONFIG_DEFAULTS["formatters"]["generic"][
"class"
] = "json_logging.JSONLogFormatter"
del LOGGING_CONFIG_DEFAULTS["formatters"]["generic"]["format"]
LOGGING_CONFIG_DEFAULTS["formatters"]["access"][
"class"
] = "json_logging.JSONLogFormatter"
del LOGGING_CONFIG_DEFAULTS["formatters"]["access"]["format"]
# logging.config.dictConfig(LOGGING_CONFIG_DEFAULTS)
|
(self)
|
710,462
|
json_logging.framework.sanic
|
SanicAppRequestInstrumentationConfigurator
| null |
class SanicAppRequestInstrumentationConfigurator(AppRequestInstrumentationConfigurator):
def config(self, app, exclude_url_patterns=[]):
if not is_sanic_present():
raise RuntimeError("Sanic is not available in system runtime")
# noinspection PyPackageRequirements
from sanic import Sanic
if not isinstance(app, Sanic):
raise RuntimeError("app is not a valid Sanic.app.Sanic app instance")
# noinspection PyAttributeOutsideInit
self.request_logger = logging.getLogger("sanic-request")
logging.getLogger("sanic.access").disabled = True
@app.middleware("request")
def before_request(request):
if is_not_match_any_pattern(request.path, exclude_url_patterns):
request.ctx.request_info = json_logging.RequestInfo(request)
@app.middleware("response")
def after_request(request, response):
if hasattr(request.ctx, "request_info"):
request_info = request.ctx.request_info
request_info.update_response_status(response)
self.request_logger.info(
"", extra={"request_info": request_info, "type": "request"}
)
def get_request_logger(self):
return self.request_logger
|
(*args, **kw)
|
710,464
|
json_logging.framework.sanic
|
config
| null |
def config(self, app, exclude_url_patterns=[]):
if not is_sanic_present():
raise RuntimeError("Sanic is not available in system runtime")
# noinspection PyPackageRequirements
from sanic import Sanic
if not isinstance(app, Sanic):
raise RuntimeError("app is not a valid Sanic.app.Sanic app instance")
# noinspection PyAttributeOutsideInit
self.request_logger = logging.getLogger("sanic-request")
logging.getLogger("sanic.access").disabled = True
@app.middleware("request")
def before_request(request):
if is_not_match_any_pattern(request.path, exclude_url_patterns):
request.ctx.request_info = json_logging.RequestInfo(request)
@app.middleware("response")
def after_request(request, response):
if hasattr(request.ctx, "request_info"):
request_info = request.ctx.request_info
request_info.update_response_status(response)
self.request_logger.info(
"", extra={"request_info": request_info, "type": "request"}
)
|
(self, app, exclude_url_patterns=[])
|
710,465
|
json_logging.framework.sanic
|
get_request_logger
| null |
def get_request_logger(self):
return self.request_logger
|
(self)
|
710,466
|
json_logging.framework.sanic
|
SanicRequestAdapter
| null |
class SanicRequestAdapter(RequestAdapter):
@staticmethod
def get_current_request():
raise NotImplementedError
@staticmethod
def support_global_request_object():
return False
# noinspection PyPackageRequirements
@staticmethod
def get_request_class_type():
from sanic.request import Request
return Request
def get_remote_user(self, request):
# todo: implement it
return None
def get_http_header(self, request, header_name, default=None):
if header_name in request.headers:
return request.headers.get(header_name)
return default
def set_correlation_id(self, request, value):
request.ctx.correlation_id = value
def get_correlation_id_in_request_context(self, request):
try:
return request.ctx.correlation_id
except AttributeError:
return None
def get_protocol(self, request):
return json_logging.EMPTY_VALUE
def get_path(self, request):
return request.path
def get_content_length(self, request):
return json_logging.EMPTY_VALUE
def get_method(self, request):
return request.method
def get_remote_ip(self, request):
return request.ip
def get_remote_port(self, request):
return json_logging.EMPTY_VALUE
|
(*arg, **kwargs)
|
710,468
|
json_logging.framework.sanic
|
get_content_length
| null |
def get_content_length(self, request):
return json_logging.EMPTY_VALUE
|
(self, request)
|
710,469
|
json_logging.framework.sanic
|
get_correlation_id_in_request_context
| null |
def get_correlation_id_in_request_context(self, request):
try:
return request.ctx.correlation_id
except AttributeError:
return None
|
(self, request)
|
710,470
|
json_logging.framework.sanic
|
get_current_request
| null |
@staticmethod
def get_current_request():
raise NotImplementedError
|
()
|
710,471
|
json_logging.framework.sanic
|
get_http_header
| null |
def get_http_header(self, request, header_name, default=None):
if header_name in request.headers:
return request.headers.get(header_name)
return default
|
(self, request, header_name, default=None)
|
710,472
|
json_logging.framework.sanic
|
get_method
| null |
def get_method(self, request):
return request.method
|
(self, request)
|
710,473
|
json_logging.framework.sanic
|
get_path
| null |
def get_path(self, request):
return request.path
|
(self, request)
|
710,474
|
json_logging.framework.sanic
|
get_protocol
| null |
def get_protocol(self, request):
return json_logging.EMPTY_VALUE
|
(self, request)
|
710,475
|
json_logging.framework.sanic
|
get_remote_ip
| null |
def get_remote_ip(self, request):
return request.ip
|
(self, request)
|
710,476
|
json_logging.framework.sanic
|
get_remote_port
| null |
def get_remote_port(self, request):
return json_logging.EMPTY_VALUE
|
(self, request)
|
710,477
|
json_logging.framework.sanic
|
get_remote_user
| null |
def get_remote_user(self, request):
# todo: implement it
return None
|
(self, request)
|
710,478
|
json_logging.framework.sanic
|
get_request_class_type
| null |
@staticmethod
def get_request_class_type():
from sanic.request import Request
return Request
|
()
|
710,479
|
json_logging.framework.sanic
|
set_correlation_id
| null |
def set_correlation_id(self, request, value):
request.ctx.correlation_id = value
|
(self, request, value)
|
710,480
|
json_logging.framework.sanic
|
support_global_request_object
| null |
@staticmethod
def support_global_request_object():
return False
|
()
|
710,481
|
json_logging.framework.sanic
|
SanicResponseAdapter
| null |
class SanicResponseAdapter(ResponseAdapter):
def get_status_code(self, response):
return response.status
def get_response_size(self, response):
return json_logging.EMPTY_VALUE
def get_content_type(self, response):
return response.content_type
|
(*arg, **kwargs)
|
710,483
|
json_logging.framework.sanic
|
get_content_type
| null |
def get_content_type(self, response):
return response.content_type
|
(self, response)
|
710,484
|
json_logging.framework.sanic
|
get_response_size
| null |
def get_response_size(self, response):
return json_logging.EMPTY_VALUE
|
(self, response)
|
710,485
|
json_logging.framework.sanic
|
get_status_code
| null |
def get_status_code(self, response):
return response.status
|
(self, response)
|
710,486
|
json_logging
|
__init
|
Initialize JSON logging support, if no **framework_name** passed, logging will be initialized in non-web context.
This is supposed to be called only one time.
If **custom_formatter** is passed, it will (in non-web context) use this formatter over the default.
:param framework_name: type of framework logging should support.DEFAULT_CORRELATION_ID_HEADERS
:param custom_formatter: formatter to override default JSONLogFormatter.
|
def __init(framework_name=None, custom_formatter=None, enable_json=False):
"""
Initialize JSON logging support, if no **framework_name** passed, logging will be initialized in non-web context.
This is supposed to be called only one time.
If **custom_formatter** is passed, it will (in non-web context) use this formatter over the default.
:param framework_name: type of framework logging should support.DEFAULT_CORRELATION_ID_HEADERS
:param custom_formatter: formatter to override default JSONLogFormatter.
"""
global _current_framework
global ENABLE_JSON_LOGGING
global _default_formatter
ENABLE_JSON_LOGGING = enable_json
if _current_framework is not None:
raise RuntimeError("Can not call init more than once")
if custom_formatter:
if not issubclass(custom_formatter, logging.Formatter):
raise ValueError('custom_formatter is not subclass of logging.Formatter', custom_formatter)
ENABLE_JSON_LOGGING_DEBUG and _logger.info("init framework " + str(framework_name))
if framework_name:
framework_name = framework_name.lower()
if framework_name not in _framework_support_map.keys():
raise RuntimeError(framework_name + " is not a supported framework")
_current_framework = _framework_support_map[framework_name]
global _request_util
_request_util = util.RequestUtil(request_adapter_class=_current_framework['request_adapter_class'],
response_adapter_class=_current_framework['response_adapter_class'])
if ENABLE_JSON_LOGGING and _current_framework['app_configurator'] is not None:
_current_framework['app_configurator']().config()
_default_formatter = custom_formatter if custom_formatter else JSONLogWebFormatter
else:
_default_formatter = custom_formatter if custom_formatter else JSONLogFormatter
if not enable_json and not ENABLE_JSON_LOGGING:
_logger.warning(
"JSON format is not enabled, normal log will be in plain text but request logging still in JSON format! "
"To enable set ENABLE_JSON_LOGGING env var to either one of following values: ['true', '1', 'y', 'yes']")
else:
ENABLE_JSON_LOGGING = True
logging._defaultFormatter = _default_formatter()
# go to all the initialized logger and update it to use JSON formatter
ENABLE_JSON_LOGGING_DEBUG and _logger.debug("Update all existing logger to using JSONLogFormatter")
existing_loggers = list(map(logging.getLogger, logging.Logger.manager.loggerDict))
util.update_formatter_for_loggers(existing_loggers, _default_formatter)
|
(framework_name=None, custom_formatter=None, enable_json=False)
|
710,487
|
json_logging
|
_sanitize_log_msg
| null |
def _sanitize_log_msg(record):
return record.getMessage().replace('\n', '_').replace('\r', '_').replace('\t', '_')
|
(record)
|
710,488
|
json_logging
|
config_root_logger
|
You must call this if you are using root logger.
Make all root logger' handlers produce JSON format
& remove duplicate handlers for request instrumentation logging.
Please made sure that you call this after you called "logging.basicConfig() or logging.getLogger()
|
def config_root_logger():
"""
You must call this if you are using root logger.
Make all root logger' handlers produce JSON format
& remove duplicate handlers for request instrumentation logging.
Please made sure that you call this after you called "logging.basicConfig() or logging.getLogger()
"""
if not logging.root.handlers:
_logger.error(
"No logging handlers found for root logger. Please made sure that you call this after you called "
"logging.basicConfig() or logging.getLogger()")
return
if ENABLE_JSON_LOGGING:
ENABLE_JSON_LOGGING_DEBUG and _logger.debug("Update root logger to using JSONLogFormatter")
global _default_formatter
util.update_formatter_for_loggers([logging.root], _default_formatter)
|
()
|
710,495
|
json_logging
|
get_correlation_id
|
Get current request correlation-id. If one is not present, a new one might be generated
depends on CREATE_CORRELATION_ID_IF_NOT_EXISTS setting value.
:return: correlation-id string
|
def get_correlation_id(request=None):
"""
Get current request correlation-id. If one is not present, a new one might be generated
depends on CREATE_CORRELATION_ID_IF_NOT_EXISTS setting value.
:return: correlation-id string
"""
return _request_util.get_correlation_id(request=request)
|
(request=None)
|
710,496
|
json_logging.util
|
get_library_logger
|
:param logger_name: name
:return: logger
|
def get_library_logger(logger_name):
"""
:param logger_name: name
:return: logger
"""
# noinspection PyUnresolvedReferences
if logger_name in logging.Logger.manager.loggerDict:
return logging.getLogger(logger_name)
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
# add stdout output in case parent have no handlers
if len(logger.parent.handlers) == 0:
logger.addHandler(StreamHandler(sys.stdout))
return logger
|
(logger_name)
|
710,497
|
json_logging
|
get_request_logger
| null |
def get_request_logger():
global _request_logger
if _current_framework is None or _current_framework == '-':
raise RuntimeError(
"request_logger is only available if json_logging is inited with a web app, "
"call init_<framework_name>() to do that")
instance = _current_framework['app_request_instrumentation_configurator']._instance
if instance is None:
raise RuntimeError("please init request instrument first, call init_request_instrument(app) to do that")
return instance.request_logger
|
()
|
710,498
|
json_logging
|
init_connexion
| null |
def init_connexion(custom_formatter=None, enable_json=False):
__init(framework_name='connexion', custom_formatter=custom_formatter, enable_json=enable_json)
|
(custom_formatter=None, enable_json=False)
|
710,499
|
json_logging
|
init_fastapi
| null |
def init_fastapi(custom_formatter=None, enable_json=False):
__init(framework_name='fastapi', custom_formatter=custom_formatter, enable_json=enable_json)
|
(custom_formatter=None, enable_json=False)
|
710,500
|
json_logging
|
init_flask
| null |
def init_flask(custom_formatter=None, enable_json=False):
__init(framework_name='flask', custom_formatter=custom_formatter, enable_json=enable_json)
|
(custom_formatter=None, enable_json=False)
|
710,501
|
json_logging
|
init_non_web
| null |
def init_non_web(*args, **kw):
__init(*args, **kw)
|
(*args, **kw)
|
710,502
|
json_logging
|
init_quart
| null |
def init_quart(custom_formatter=None, enable_json=False):
__init(framework_name='quart', custom_formatter=custom_formatter, enable_json=enable_json)
|
(custom_formatter=None, enable_json=False)
|
710,503
|
json_logging
|
init_request_instrument
|
Configure the request instrumentation logging configuration for given web app. Must be called after init method
If **custom_formatter** is passed, it will use this formatter over the default.
:param app: current web application instance
:param custom_formatter: formatter to override default JSONRequestLogFormatter.
|
def init_request_instrument(app=None, custom_formatter=None, exclude_url_patterns=[]):
"""
Configure the request instrumentation logging configuration for given web app. Must be called after init method
If **custom_formatter** is passed, it will use this formatter over the default.
:param app: current web application instance
:param custom_formatter: formatter to override default JSONRequestLogFormatter.
"""
if _current_framework is None or _current_framework == '-':
raise RuntimeError("please init the logging first, call init(framework_name) first")
if custom_formatter:
if not issubclass(custom_formatter, logging.Formatter):
raise ValueError('custom_formatter is not subclass of logging.Formatter', custom_formatter)
configurator = _current_framework['app_request_instrumentation_configurator']()
configurator.config(app, exclude_url_patterns=exclude_url_patterns)
formatter = custom_formatter if custom_formatter else JSONRequestLogFormatter
request_logger = configurator.request_logger
request_logger.setLevel(logging.DEBUG)
request_logger.addHandler(logging.StreamHandler(sys.stdout))
util.update_formatter_for_loggers([request_logger], formatter)
request_logger.parent = None
|
(app=None, custom_formatter=None, exclude_url_patterns=[])
|
710,504
|
json_logging
|
init_sanic
| null |
def init_sanic(custom_formatter=None, enable_json=False):
__init(framework_name='sanic', custom_formatter=custom_formatter, enable_json=enable_json)
|
(custom_formatter=None, enable_json=False)
|
710,505
|
json_logging.util
|
is_env_var_toggle
| null |
def is_env_var_toggle(var_name):
enable_json_setting = str(os.getenv(var_name)).lower()
_env_toggle = enable_json_setting.lower() in ['true', '1', 'y', 'yes']
return _env_toggle
|
(var_name)
|
710,509
|
json_logging
|
register_framework_support
|
register support for a framework
:param name: name of framework
:param app_configurator: app pre-configurator class
:param app_request_instrumentation_configurator: app configurator class
:param request_adapter_class: request adapter class
:param response_adapter_class: response adapter class
|
def register_framework_support(name, app_configurator, app_request_instrumentation_configurator, request_adapter_class,
response_adapter_class):
"""
register support for a framework
:param name: name of framework
:param app_configurator: app pre-configurator class
:param app_request_instrumentation_configurator: app configurator class
:param request_adapter_class: request adapter class
:param response_adapter_class: response adapter class
"""
if not name:
raise RuntimeError("framework name can not be null or empty")
util.validate_subclass(request_adapter_class, RequestAdapter)
util.validate_subclass(response_adapter_class, ResponseAdapter)
util.validate_subclass(app_request_instrumentation_configurator, AppRequestInstrumentationConfigurator)
if app_configurator is not None:
util.validate_subclass(app_configurator, FrameworkConfigurator)
name = name.lower()
if name in _framework_support_map:
ENABLE_JSON_LOGGING_DEBUG and _logger.warning("Re-register framework %s", name)
_framework_support_map[name] = {
'app_configurator': app_configurator,
'app_request_instrumentation_configurator': app_request_instrumentation_configurator,
'request_adapter_class': request_adapter_class,
'response_adapter_class': response_adapter_class
}
|
(name, app_configurator, app_request_instrumentation_configurator, request_adapter_class, response_adapter_class)
|
710,597
|
pytest_repeat
|
UnexpectedError
| null |
class UnexpectedError(Exception):
pass
| null |
710,600
|
pytest_repeat
|
pytest_addoption
| null |
def pytest_addoption(parser):
parser.addoption(
'--count',
action='store',
default=1,
type=int,
help='Number of times to repeat each test')
parser.addoption(
'--repeat-scope',
action='store',
default='function',
type=str,
choices=('function', 'class', 'module', 'session'),
help='Scope for repeating tests')
|
(parser)
|
710,601
|
pytest_repeat
|
pytest_configure
| null |
def pytest_configure(config):
config.addinivalue_line(
'markers',
'repeat(n): run the given test function `n` times.')
|
(config)
|
710,602
|
pytest_repeat
|
pytest_generate_tests
| null |
@pytest.hookimpl(trylast=True)
def pytest_generate_tests(metafunc):
count = metafunc.config.option.count
m = metafunc.definition.get_closest_marker('repeat')
if m is not None:
count = int(m.args[0])
if count > 1:
metafunc.fixturenames.append("__pytest_repeat_step_number")
def make_progress_id(i, n=count):
return '{0}-{1}'.format(i + 1, n)
scope = metafunc.config.option.repeat_scope
metafunc.parametrize(
'__pytest_repeat_step_number',
range(count),
indirect=True,
ids=make_progress_id,
scope=scope
)
|
(metafunc)
|
710,604
|
referencing._core
|
Anchor
|
A simple anchor in a `Resource`.
|
class Anchor(Generic[D]):
"""
A simple anchor in a `Resource`.
"""
name: str
resource: Resource[D]
def resolve(self, resolver: Resolver[D]):
"""
Return the resource for this anchor.
"""
return Resolved(contents=self.resource.contents, resolver=resolver)
|
(name: str, resource: referencing._core.Resource[~D]) -> None
|
710,606
|
referencing._core
|
__eq__
|
Method generated by attrs for class Anchor.
|
from __future__ import annotations
from collections.abc import Iterable, Iterator, Sequence
from enum import Enum
from typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar
from urllib.parse import unquote, urldefrag, urljoin
from attrs import evolve, field
from rpds import HashTrieMap, HashTrieSet, List
from referencing import exceptions
from referencing._attrs import frozen
from referencing.typing import URI, Anchor as AnchorType, D, Mapping, Retrieve
EMPTY_UNCRAWLED: HashTrieSet[URI] = HashTrieSet()
EMPTY_PREVIOUS_RESOLVERS: List[URI] = List()
class _Unset(Enum):
"""
What sillyness...
"""
SENTINEL = 1
|
(self, other)
|
710,611
|
referencing._core
|
__ne__
|
Method generated by attrs for class Anchor.
| null |
(self, other)
|
710,615
|
referencing._core
|
resolve
|
Return the resource for this anchor.
|
def resolve(self, resolver: Resolver[D]):
"""
Return the resource for this anchor.
"""
return Resolved(contents=self.resource.contents, resolver=resolver)
|
(self, resolver: referencing._core.Resolver[~D])
|
710,662
|
referencing._core
|
Specification
|
A specification which defines referencing behavior.
The various methods of a `Specification` allow for varying referencing
behavior across JSON Schema specification versions, etc.
|
class Specification(Generic[D]):
"""
A specification which defines referencing behavior.
The various methods of a `Specification` allow for varying referencing
behavior across JSON Schema specification versions, etc.
"""
#: A short human-readable name for the specification, used for debugging.
name: str
#: Find the ID of a given document.
id_of: Callable[[D], URI | None]
#: Retrieve the subresources of the given document (without traversing into
#: the subresources themselves).
subresources_of: Callable[[D], Iterable[D]]
#: While resolving a JSON pointer, conditionally enter a subresource
#: (if e.g. we have just entered a keyword whose value is a subresource)
maybe_in_subresource: _MaybeInSubresource[D]
#: Retrieve the anchors contained in the given document.
_anchors_in: Callable[
[Specification[D], D],
Iterable[AnchorType[D]],
] = field(alias="anchors_in")
#: An opaque specification where resources have no subresources
#: nor internal identifiers.
OPAQUE: ClassVar[Specification[Any]]
#: Attempt to discern which specification applies to the given contents.
#:
#: May be called either as an instance method or as a class method, with
#: slightly different behavior in the following case:
#:
#: Recall that not all contents contains enough internal information about
#: which specification it is written for -- the JSON Schema ``{}``,
#: for instance, is valid under many different dialects and may be
#: interpreted as any one of them.
#:
#: When this method is used as an instance method (i.e. called on a
#: specific specification), that specification is used as the default
#: if the given contents are unidentifiable.
#:
#: On the other hand when called as a class method, an error is raised.
#:
#: To reiterate, ``DRAFT202012.detect({})`` will return ``DRAFT202012``
#: whereas the class method ``Specification.detect({})`` will raise an
#: error.
#:
#: (Note that of course ``DRAFT202012.detect(...)`` may return some other
#: specification when given a schema which *does* identify as being for
#: another version).
#:
#: Raises:
#:
#: `CannotDetermineSpecification`
#:
#: if the given contents don't have any discernible
#: information which could be used to guess which
#: specification they identify as
detect = _SpecificationDetector()
def __repr__(self) -> str:
return f"<Specification name={self.name!r}>"
def anchors_in(self, contents: D):
"""
Retrieve the anchors contained in the given document.
"""
return self._anchors_in(self, contents)
def create_resource(self, contents: D) -> Resource[D]:
"""
Create a resource which is interpreted using this specification.
"""
return Resource(contents=contents, specification=self)
|
(name: str, id_of: Callable[[~D], str | None], subresources_of: Callable[[~D], collections.abc.Iterable[~D]], maybe_in_subresource: referencing._core._MaybeInSubresource[~D], anchors_in: 'Callable[[Specification[D], D], Iterable[AnchorType[D]]]') -> None
|
710,664
|
referencing._core
|
__eq__
|
Method generated by attrs for class Specification.
|
from __future__ import annotations
from collections.abc import Iterable, Iterator, Sequence
from enum import Enum
from typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar
from urllib.parse import unquote, urldefrag, urljoin
from attrs import evolve, field
from rpds import HashTrieMap, HashTrieSet, List
from referencing import exceptions
from referencing._attrs import frozen
from referencing.typing import URI, Anchor as AnchorType, D, Mapping, Retrieve
EMPTY_UNCRAWLED: HashTrieSet[URI] = HashTrieSet()
EMPTY_PREVIOUS_RESOLVERS: List[URI] = List()
class _Unset(Enum):
"""
What sillyness...
"""
SENTINEL = 1
|
(self, other)
|
710,669
|
referencing._core
|
__ne__
|
Method generated by attrs for class Specification.
| null |
(self, other)
|
710,670
|
referencing._core
|
__repr__
| null |
def __repr__(self) -> str:
return f"<Specification name={self.name!r}>"
|
(self) -> str
|
710,673
|
referencing._core
|
anchors_in
|
Retrieve the anchors contained in the given document.
|
def anchors_in(self, contents: D):
"""
Retrieve the anchors contained in the given document.
"""
return self._anchors_in(self, contents)
|
(self, contents: ~D)
|
710,674
|
referencing._core
|
create_resource
|
Create a resource which is interpreted using this specification.
|
def create_resource(self, contents: D) -> Resource[D]:
"""
Create a resource which is interpreted using this specification.
"""
return Resource(contents=contents, specification=self)
|
(self, contents: ~D) -> referencing._core.Resource[~D]
|
710,675
|
referencing._core
|
_detect_or_error
| null |
def _detect_or_error(contents: D) -> Specification[D]:
if not isinstance(contents, Mapping):
raise exceptions.CannotDetermineSpecification(contents)
jsonschema_dialect_id = contents.get("$schema") # type: ignore[reportUnknownMemberType]
if not isinstance(jsonschema_dialect_id, str):
raise exceptions.CannotDetermineSpecification(contents)
from referencing.jsonschema import specification_with
return specification_with(jsonschema_dialect_id)
|
(contents: ~D) -> referencing._core.Specification[~D]
|
710,682
|
langchain_core._api.beta_decorator
|
surface_langchain_beta_warnings
|
Unmute LangChain beta warnings.
|
def surface_langchain_beta_warnings() -> None:
"""Unmute LangChain beta warnings."""
warnings.filterwarnings(
"default",
category=LangChainBetaWarning,
)
|
() -> NoneType
|
710,684
|
yt_dlp.utils
|
DateRange
|
Represents a time interval between two dates
|
from yt_dlp.utils import DateRange
|
(start=None, end=None)
|
710,685
|
yt_dlp.utils
|
__contains__
|
Check if the date is in the range
| null |
(self, date)
|
710,687
|
yt_dlp.utils
|
__init__
|
start and end must be strings in the format accepted by date
| null |
(self, start=None, end=None)
|
710,690
|
yt_dlp.utils
|
DownloadCancelled
|
Exception raised when the download queue should be interrupted
|
from yt_dlp.utils import DownloadCancelled
|
(msg=None)
|
710,692
|
yt_dlp.utils
|
DownloadError
|
Download Error exception.
This exception may be thrown by FileDownloader objects if they are not
configured to continue on errors. They will contain the appropriate
error message.
|
from yt_dlp.utils import DownloadError
|
(msg, exc_info=None)
|
710,693
|
yt_dlp.utils
|
__init__
|
exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()).
| null |
(self, msg, exc_info=None)
|
710,694
|
yt_dlp.postprocessor.ffmpeg
|
FFmpegExtractAudioPP
| null |
class FFmpegExtractAudioPP(FFmpegPostProcessor):
COMMON_AUDIO_EXTS = MEDIA_EXTENSIONS.common_audio + ('wma', )
SUPPORTED_EXTS = tuple(ACODECS.keys())
FORMAT_RE = create_mapping_re(('best', *SUPPORTED_EXTS))
def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
FFmpegPostProcessor.__init__(self, downloader)
self.mapping = preferredcodec or 'best'
self._preferredquality = float_or_none(preferredquality)
self._nopostoverwrites = nopostoverwrites
def _quality_args(self, codec):
if self._preferredquality is None:
return []
elif self._preferredquality > 10:
return ['-b:a', f'{self._preferredquality}k']
limits = {
'libmp3lame': (10, 0),
'libvorbis': (0, 10),
# FFmpeg's AAC encoder does not have an upper limit for the value of -q:a.
# Experimentally, with values over 4, bitrate changes were minimal or non-existent
'aac': (0.1, 4),
'libfdk_aac': (1, 5),
}.get(codec)
if not limits:
return []
q = limits[1] + (limits[0] - limits[1]) * (self._preferredquality / 10)
if codec == 'libfdk_aac':
return ['-vbr', f'{int(q)}']
return ['-q:a', f'{q}']
def run_ffmpeg(self, path, out_path, codec, more_opts):
if codec is None:
acodec_opts = []
else:
acodec_opts = ['-acodec', codec]
opts = ['-vn'] + acodec_opts + more_opts
try:
FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
except FFmpegPostProcessorError as err:
raise PostProcessingError(f'audio conversion failed: {err.msg}')
@PostProcessor._restrict_to(images=False)
def run(self, information):
orig_path = path = information['filepath']
target_format, _skip_msg = resolve_mapping(information['ext'], self.mapping)
if target_format == 'best' and information['ext'] in self.COMMON_AUDIO_EXTS:
target_format, _skip_msg = None, 'the file is already in a common audio format'
if not target_format:
self.to_screen(f'Not converting audio {orig_path}; {_skip_msg}')
return [], information
filecodec = self.get_audio_codec(path)
if filecodec is None:
raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
if filecodec == 'aac' and target_format in ('m4a', 'best'):
# Lossless, but in another container
extension, _, more_opts, acodec = *ACODECS['m4a'], 'copy'
elif target_format == 'best' or target_format == filecodec:
# Lossless if possible
try:
extension, _, more_opts, acodec = *ACODECS[filecodec], 'copy'
except KeyError:
extension, acodec, more_opts = ACODECS['mp3']
else:
# We convert the audio (lossy if codec is lossy)
extension, acodec, more_opts = ACODECS[target_format]
if acodec == 'aac' and self._features.get('fdk'):
acodec, more_opts = 'libfdk_aac', []
more_opts = list(more_opts)
if acodec != 'copy':
more_opts = self._quality_args(acodec)
temp_path = new_path = replace_extension(path, extension, information['ext'])
if new_path == path:
if acodec == 'copy':
self.to_screen(f'Not converting audio {orig_path}; file is already in target format {target_format}')
return [], information
orig_path = prepend_extension(path, 'orig')
temp_path = prepend_extension(path, 'temp')
if (self._nopostoverwrites and os.path.exists(encodeFilename(new_path))
and os.path.exists(encodeFilename(orig_path))):
self.to_screen('Post-process file %s exists, skipping' % new_path)
return [], information
self.to_screen(f'Destination: {new_path}')
self.run_ffmpeg(path, temp_path, acodec, more_opts)
os.replace(path, orig_path)
os.replace(temp_path, new_path)
information['filepath'] = new_path
information['ext'] = extension
# Try to update the date time for extracted audio file.
if information.get('filetime') is not None:
self.try_utime(
new_path, time.time(), information['filetime'], errnote='Cannot update utime of audio file')
return [orig_path], information
|
(downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.