| 1 |
#------------------------------------------------------------------------- |
| 2 |
# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 |
# Licensed under the MIT License. See License.txt in the project root for |
| 4 |
# license information. |
| 5 |
#-------------------------------------------------------------------------- |
| 6 |
|
| 7 |
# Python imports |
| 8 |
from enum import Enum |
| 9 |
import logging |
| 10 |
import io |
| 11 |
|
| 12 |
# C imports |
| 13 |
from libc.stdlib cimport malloc, free |
| 14 |
cimport c_xlogging |
| 15 |
|
| 16 |
|
| 17 |
_logger = logging.getLogger('uamqp.c_uamqp') |
| 18 |
|
| 19 |
|
| 20 |
class LogCategory(Enum): |
| 21 |
Error = c_xlogging.LOG_CATEGORY_TAG.AZ_LOG_ERROR |
| 22 |
Info = c_xlogging.LOG_CATEGORY_TAG.AZ_LOG_INFO |
| 23 |
Debug = c_xlogging.LOG_CATEGORY_TAG.AZ_LOG_TRACE |
| 24 |
|
| 25 |
|
| 26 |
cdef char* vprintf_alloc(const char* format, c_xlogging.va_list va): |
| 27 |
cdef char* result |
| 28 |
cdef c_xlogging.va_list va_copy |
| 29 |
cdef int neededSize |
| 30 |
c_xlogging.va_copy(va_copy, va); |
| 31 |
neededSize = c_xlogging.vsnprintf(NULL, 0, format, va_copy) |
| 32 |
c_xlogging.va_end(va_copy) |
| 33 |
|
| 34 |
if neededSize < 0: |
| 35 |
result = NULL |
| 36 |
else: |
| 37 |
result = <char*>malloc(neededSize + 1) |
| 38 |
if <void*>result != NULL: |
| 39 |
if c_xlogging.vsnprintf(result, neededSize + 1, format, va) != neededSize: |
| 40 |
free(result) |
| 41 |
result = NULL |
| 42 |
return result; |
| 43 |
|
| 44 |
|
| 45 |
cdef void custom_logging_function(c_xlogging.LOG_CATEGORY_TAG log_category, const char* file, const char* func, const int line, unsigned int options, const char* format, ...): |
| 46 |
log_level = LogCategory(log_category) |
| 47 |
cdef c_xlogging.va_list args |
| 48 |
cdef char* text |
| 49 |
c_xlogging.va_start(args, format) |
| 50 |
try: |
| 51 |
text = vprintf_alloc(format, args) |
| 52 |
if <void*>text != NULL: |
| 53 |
_python_log(log_level, text, bool(options), file=file, func=func, line=line) |
| 54 |
except KeyboardInterrupt: |
| 55 |
pass |
| 56 |
finally: |
| 57 |
c_xlogging.va_end(args) |
| 58 |
if <void*>text != NULL: |
| 59 |
free(text) |
| 60 |
|
| 61 |
|
| 62 |
cpdef set_python_logger(): |
| 63 |
c_xlogging.xlogging_set_log_function(<c_xlogging.LOGGER_LOG>custom_logging_function) |
| 64 |
|
| 65 |
|
| 66 |
def _python_log(category, text, end, text_bldr=[], file=None, func=None, line=None): |
| 67 |
text_bldr.append(text) |
| 68 |
if not end: |
| 69 |
return |
| 70 |
|
| 71 |
log_line = b'' |
| 72 |
while text_bldr: |
| 73 |
log_line += text_bldr.pop(0) |
| 74 |
if category == LogCategory.Debug or category == LogCategory.Info: |
| 75 |
_logger.info("%r", log_line) |
| 76 |
else: |
| 77 |
_logger.info("%r (%r:%r:%r)", log_line, file, func, line) |