# -*- coding: utf-8 -*-
"""
Module comet/pyhed
"""
# COMET - COupled Magnetic resonance Electrical resistivity Tomography
# Copyright (C) 2019 Nico Skibbe
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import logging
import sys
from contextlib import contextmanager
log = logging.getLogger('comet')
from . config import config, SecondaryConfig
# simple submodule import
from . import hed
from . import misc
from . import loop
from . import IO
from . import plot
[docs]def addLogFile(name=None, new_log=True):
import os
from pathlib import Path
import inspect
if name is None:
# take basename of the script
name = inspect.stack()[1][1]
name = Path(name).with_suffix('.log')
else:
if name.endswith('.py'):
name = Path(name).with_suffix('.log')
log.warning(
'addLogFile: Changed file suffix from ".py" to ".log"'
' to ensure no python script is accidentally overridden.')
else:
name = Path(name)
if new_log:
if name.exists():
os.remove(name)
# search for entries of the same file handler (previous calls)
remove = []
for hdl_id, hdl in enumerate(log.handlers):
if isinstance(hdl, logging.FileHandler):
if hdl.baseFilename == name.as_posix():
remove.append(hdl_id)
# remove double entries
for hdid in remove[::-1]:
log.handlers.pop(hdid)
# add new file handler
fh = logging.FileHandler(name)
with open(name, mode='a') as quickanddirty:
quickanddirty.write('#' * 34 + ' SOURCE CODE ' + '#' * 33 + '\n')
for line in inspect.getsourcelines(inspect.stack()[1][0])[0]:
quickanddirty.write(line)
quickanddirty.write('#' * 38 + ' LOG ' + '#' * 37 + '\n')
formatter = logging.Formatter(
fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
fh.setFormatter(formatter)
log.addHandler(fh)
if 'pygimli' in sys.modules:
logging.getLogger('pyGIMLi').addHandler(fh)
log.info('Inititalised File Handler: {}'.format(name))
log.info('used modules information:')
keep_track = ['pygimli', 'pybert', 'custEM',
'comet', 'numpy', 'matplotlib']
for item in keep_track:
if item in sys.modules:
module = sys.modules[item]
log.info('{}, version: {}'.format(module, module.__version__))
@contextmanager
def temporalLoglevel(lglvl, logger='comet'):
tempLog = logging.getLogger(logger)
old_lvl = tempLog.getEffectiveLevel()
try:
tempLog.setLevel(lglvl)
yield
finally:
tempLog.setLevel(old_lvl)
#class Params(object):
# def __init__(self):
# self.use_kk_hankel = False
#
# def useKerryKeyHankel(self, boolean: bool, not_found_ok=False):
# if boolean is True:
#
# try:
# import empymod as em
# log.info('Enable use of Kerry Key Hankel factors through'
# ' empymod.')
#
# except ModuleNotFoundError as e:
# if not_found_ok:
# log.warning('Empymod is not installed. Use standard hankel'
# ' factors instead.')
# boolean = False
#
# log.critical('The use of Kerry Key Hankel factors is only '
# 'possible if empymod is installed.')
# raise e
#
# self.use_kk_hankel = boolean
#params = Params()
__all__ = ('log', 'config', 'SecondaryConfig', 'hed', 'misc', 'loop', 'IO',
'plot', 'addLogFile') # , 'params')
# log level as taken from fenics
# log.setLevel(logging.WARNING)
# CRITICAL = 50, errors that may lead to data corruption and suchlike
# ERROR = 40, things that go boom
# WARNING = 30, things that may go boom later
# INFO = 20, information of general interest
# PROGRESS = 16, what's happening (broadly), only in fenics
# TRACE = 13, what's happening (in detail), only in fenics
# DBG = 10 sundry
# THE END