|
| 1 | +# Data Parallel Control (dpctl) |
| 2 | +# |
| 3 | +# Copyright 2020-2021 Intel Corporation |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +# distutils: language = c++ |
| 18 | +# cython: language_level=3 |
| 19 | +# cython: linetrace=True |
| 20 | + |
| 21 | +""" Implements developer utilities. |
| 22 | +""" |
| 23 | +import contextlib |
| 24 | +import os |
| 25 | + |
| 26 | + |
| 27 | +cdef extern from "syclinterface/dpctl_service.h": |
| 28 | + cdef void DPCTLService_InitLogger(const char *, const char *) |
| 29 | + cdef void DPCTLService_ShutdownLogger() |
| 30 | + |
| 31 | + |
| 32 | +def init_logger(log_dir=None): |
| 33 | + """Initialize logger to use given directory to save logs. |
| 34 | +
|
| 35 | + The call has no effect if `dpctl` was not built to use logger. |
| 36 | + """ |
| 37 | + cdef bytes p = b"" |
| 38 | + cdef const char *app_name = "dpctl" |
| 39 | + if log_dir is None: |
| 40 | + log_dir = os.getcwd() |
| 41 | + if not os.path.exists(log_dir): |
| 42 | + raise ValueError(f"Path {log_dir} does not exist") |
| 43 | + if isinstance(log_dir, str): |
| 44 | + p = bytes(log_dir, "utf-8") |
| 45 | + else: |
| 46 | + p = bytes(log_dir) |
| 47 | + DPCTLService_InitLogger(app_name, <char *>p) |
| 48 | + |
| 49 | + |
| 50 | +def fini_logger(): |
| 51 | + """Finilize logger. |
| 52 | +
|
| 53 | + The call has no effect if `dpctl` was not built to use logger. |
| 54 | + """ |
| 55 | + DPCTLService_ShutdownLogger() |
| 56 | + |
| 57 | + |
| 58 | +@contextlib.contextmanager |
| 59 | +def verbose(verbosity="warning", log_dir=None): |
| 60 | + """Context manager that activate verbosity""" |
| 61 | + _allowed_verbosity = ["warning", "error"] |
| 62 | + if not verbosity in _allowed_verbosity: |
| 63 | + raise ValueError( |
| 64 | + f"Verbosity argument not understood. " |
| 65 | + f"Permitted values are {_allowed_verbosity}" |
| 66 | + ) |
| 67 | + init_logger(log_dir=log_dir) |
| 68 | + _saved = os.environ.get("DPCTL_VERBOSITY", None) |
| 69 | + os.environ["DPCTL_VERBOSITY"] = verbosity |
| 70 | + try: |
| 71 | + yield |
| 72 | + finally: |
| 73 | + fini_logger() |
| 74 | + if _saved: |
| 75 | + os.environ["DPCTL_VERBOSITY"] = _saved |
| 76 | + else: |
| 77 | + del os.environ["DPCTL_VERBOSITY"] |
0 commit comments