def init_logger(self): balsa_log = Balsa(self.instance_name, author_name, log_directory=os.path.join('temp', 'log'), delete_existing_log_files=True) balsa_log.init_logger() self.log = get_logger(application_name)
def test_to_structured_logging(): application_name = "test_structured_logging" balsa = Balsa(application_name, __author__, verbose=True) balsa.init_logger() log = get_logger(application_name) question = "life" answer = 42 log.info(sf("test structured logging", question=question, answer=answer)) # todo: get these to work # crazy = 'a "crazy" string' # newline_string = "a\nnewline" crazy = "a crazy string" newline_string = "anewline" some_float = 3.3 a_bool = True log.info( sf("test", "more,stuff", question=question, answer=answer, newline_string=newline_string, crazy=crazy, some_float=some_float, a_bool=a_bool)) complex_value = 1 + 2j log.info(sf(complex_value=complex_value))
def test_threaded_gui(): global exception_complete timeout = 10 application_name = 'main_thread' log = get_logger(application_name) balsa = Balsa(application_name, __author__, verbose=True, log_directory='temp', gui=True, is_root=False, delete_existing_log_files=True) balsa.init_logger() log.info('starting main thread') exception_complete = False gui_thread = QtGuiThread() gui_thread.start() loop_count = 0 while gui_thread.isRunning() and loop_count < timeout: time.sleep(1) loop_count += 1 assert exception_complete exception_complete = False gui_thread = GuiThread() gui_thread.start() gui_thread.join(timeout) assert exception_complete
def test_multiprocessing(): log_directory = Path("temp", application_name) balsa = Balsa(application_name, __author__, verbose=True, log_directory=log_directory, delete_existing_log_files=True) balsa.init_logger() log = get_logger(application_name) log.info("process started") balsa_config = balsa.config_as_dict() my_process = MyProcess(balsa_config) my_process.start() my_process.join() process_log_file_path = Path(log_directory, f"{application_name}_a.log") assert process_log_file_path.exists() log_text = process_log_file_path.read_text() # check everything except the timestamp and line number assert "test_balsa_multiprocess - a - test_multiprocessing.py -" in log_text assert "- run - INFO - hello from a" in log_text log.info("process finished")
def test_balsa_simple(): application_name = 'test_balsa_simple' balsa = Balsa(application_name, __author__, is_root=False) balsa.init_logger() log = get_logger(application_name) log.error('test error message')
def test_balsa_simple(): application_name = 'test_balsa' balsa = Balsa(application_name, __author__, verbose=True, log_directory='temp', gui=True, delete_existing_log_files=True) balsa.init_logger() log = get_logger(application_name) log.error('test error message')
def run(self): # creating the balsa instance must be in the run method (not __init__() ) balsa = balsa_clone( self.parent_balsa_as_dict, self.name) # use the Process's name as the cloned logger's name balsa.init_logger() log = get_logger(application_name) log.info(f"hello from {self.name}")
def test_balsa_sentry(): application_name = "test_balsa_sentry" if "SENTRY_DSN" in os.environ: balsa = Balsa(application_name, __author__, use_sentry=True, inhibit_cloud_services=False, is_root=False, sentry_dsn=os.environ["SENTRY_DSN"]) balsa.init_logger() log = get_logger(application_name) log.error("test balsa sentry error message") else: print("Please set SENTRY_DSN environment variable to have a good %s test" % __name__)
def test_multiprocessing(): balsa = Balsa(application_name, author, verbose=True) balsa.init_logger() log = get_logger(application_name) log.info("process started") my_process = MyProcess(balsa.config_as_dict()) my_process.start() my_process.join() log.info("process finished")
def test_balsa_gui(): application_name = "test_balsa_gui" balsa = Balsa(application_name, __author__, verbose=True, log_directory="temp", gui=True, is_root=False, delete_existing_log_files=True) balsa.init_logger() log = get_logger(application_name) press_enter_thread = threading.Thread(target=press_enter) press_enter_thread.start() log.error("test error message") press_enter_thread.join()
def run(self): global exception_complete application_name = 'gui_thread' log = get_logger(application_name) try: print(f'{application_name} - before divide') a = 3.0 / 0.0 # generate an exception for testing (not a real error) except ZeroDivisionError: print(f'{application_name} - division error exception') log.error(traceback_string()) print(f'{application_name} - after error log') exception_complete = True
def test_gui_rate_limit(): application_name = "test_gui_rate_limit" balsa = Balsa(application_name, __author__, verbose=True, log_directory="temp", gui=True, is_root=False, delete_existing_log_files=True) balsa.init_logger() log = get_logger(application_name) press_enter_thread = threading.Thread(target=press_enter) press_enter_thread.start() for count in range(0, 4): log.warning(str(count)) press_enter_thread.join()
def test_balsa_sentry(): application_name = 'test_balsa_sentry' if 'SENTRY_DSN' in os.environ: balsa = Balsa(application_name, __author__, use_sentry=True, inhibit_cloud_services=False, is_root=False) balsa.init_logger() log = get_logger(application_name) log.error('test balsa sentry error message') else: print( 'Please set SENTRY_DSN environment variable to have a good %s test' % __name__)
def test_balsa_exception(): application_name = 'test_balsa_exception' balsa = Balsa(application_name, __author__, gui=True, is_root=False) balsa.rate_limits[logging.ERROR]['count'] = 4 # we have 3 messages balsa.init_logger() log = get_logger(application_name) press_enter_thread = threading.Thread(target=press_enter) press_enter_thread.start() try: a = 1.0 / 0.0 # generate an exception for testing (not a real error) except ZeroDivisionError: log.error('test exception') log.error(traceback_string()) press_enter_thread.join()
def test_two_logs(): """ test two logs where one is the root (catch-all) and other is separate (no propagation to root) """ log_names = ["a", "b", "c"] # instantiate the balsa objects # The 'a' log is the root and therefore the catch-all # The 'b' log has no propagation and is therefore only its messages balsas = { "a": Balsa("a", __author__, verbose=True), "b": Balsa("b", __author__, verbose=True, propagate=False, is_root=False) } [b.init_logger() for k, b in balsas.items()] logs = [get_logger(test_name) for test_name in log_names] # get the loggers for index, log in enumerate(logs): # log something log.info(log_names[index]) # check the contents assert len(balsas["a"].get_string_list() ) == 2 # gets the 'c' log in addition to the 'a' log assert len(balsas["b"].get_string_list()) == 1 # just the 'b' log_string_min_length = 35 # SWAG to try to ensure the log string includes the time stamp, level, etc. assert balsas["a"].get_string_list()[0][-1] == "a" assert len(balsas["a"].get_string_list()[0]) > log_string_min_length assert balsas["a"].get_string_list()[1][-1] == "c" assert len(balsas["a"].get_string_list()[1]) > log_string_min_length assert balsas["b"].get_string_list()[0][-1] == "b" assert len(balsas["b"].get_string_list()[0]) > log_string_min_length
import time import os from balsa import get_logger import propmtime import test_propmtime log = get_logger("test_propmtime") def get_mtimes(root_folder, file_path): root_mtime = os.path.getmtime(root_folder) file_mtime = os.path.getmtime(file_path) log.info('%s mtime : %f' % (root_folder, root_mtime)) log.info('%s mtime : %f' % (file_path, file_mtime)) log.info('difference : %f seconds' % (root_mtime - file_mtime)) return root_mtime, file_mtime def run(is_hidden, is_system, root=test_propmtime.data_root): current_time = time.time() file_name = 'myfile.txt' if propmtime.util.is_mac() and is_hidden: file_name = '.' + file_name file_path = os.path.join(test_propmtime.child_folder, file_name) test_propmtime.file_creator(current_time, file_path, 1, is_hidden, is_system) root_mtime, file_mtime = get_mtimes(test_propmtime.data_root, file_path) assert((root_mtime - file_mtime) >= (test_propmtime.time_offset_unit - test_propmtime.time_accuracy_window))
import os from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from balsa import get_logger from propmtime import TIMEOUT, propmtime_event, __application_name__, PropMTimePreferences log = get_logger(__application_name__) class ModHandler(FileSystemEventHandler): def __init__(self, path, app_data_folder): super().__init__() self._pmt_path = path self._app_data_folder = app_data_folder def on_any_event(self, event): super().on_any_event(event) log.debug('on_any_event : %s' % event) pref = PropMTimePreferences(self._app_data_folder) if not event.is_directory: propmtime_event(self._pmt_path, event.src_path, True, pref.get_do_hidden(), pref.get_do_system()) class PropMTimeWatcher: def __init__(self, app_data_folder): self._app_data_folder = app_data_folder self._observer = Observer()
from balsa import get_logger, Balsa application_name = 'example' log = get_logger(application_name) def main(): balsa = Balsa(application_name, 'james abel') balsa.init_logger() log.error('my error example') if __name__ == '__main__': main()
import json import shutil from functools import lru_cache from typing import Iterable import github3 from git import Repo from git.exc import GitCommandError, InvalidGitRepositoryError import appdirs from pressenter2exit import PressEnter2ExitGUI from balsa import get_logger from sundry import rmdir from backupjca import __application_name__, __author__ log = get_logger(__application_name__) def print_log(s): log.info(s) print(s) # just instantiate once @lru_cache() def get_press_enter_to_exit() -> PressEnter2ExitGUI: return PressEnter2ExitGUI(title="github local backup") def get_github_auth():
from balsa import get_logger, Balsa, __author__ log = get_logger(__file__) def my_callback(log_record): print(log_record.msg) def test_balsa_simple(): application_name = 'test_balsa' balsa = Balsa(application_name, __author__, verbose=True, log_directory='temp', error_callback=my_callback) balsa.init_logger() log.error('test error message') if __name__ == '__main__': test_balsa_simple()
from pathlib import Path import subprocess from balsa import Balsa, get_logger import appdirs from ismain import is_main from pyshipupdate import rmdir # create both 0.0.1 and 0.0.2 versions, but have the installer be of 0.0.1 to demo the upgrade to 0.0.2 app_name = "pyshipexample" author = "abel" log = get_logger(app_name) if is_main(): python_exe_path = Path("venv", "Scripts", "python.exe") balsa = Balsa(app_name, author) balsa.init_logger() # remove any old clips for d in Path(appdirs.user_data_dir(app_name, author)).glob(f"{app_name}_0.0.*"): if d.is_dir(): log.info(f"removing {str(d)}") rmdir(d) # start with 0.0.2 to create and upload the clip version_key = "__version__ = " version_file_path = Path(app_name, "__version__.py")
import argparse import sys from cmpa import __title__ from balsa import get_logger, Balsa from cmpa import Compare, __version__, __author__ log = get_logger(__title__) def main(): epilog = """ cmpa - directory compare (by abel.co) Prints the result of the directory comparison. Only the differences and the summary flag will be printed, unless verbose is given (or if silent given then nothing will be printed). - means extra files in first directory + means extra files in second directory ! means file contents mismatch = equality flag s summary process returns 1 if any mis-compares """ parser = argparse.ArgumentParser( epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter)
import argparse from balsa import get_logger, Balsa from examples import application_name, author, something_useful from examples.error_callback import balsa_example_error_callback log = get_logger(name=application_name) def main(): parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action='store_true', help='verbose') args = parser.parse_args() balsa = Balsa(application_name, author, error_callback=balsa_example_error_callback) balsa.init_logger_from_args(args) something_useful() if __name__ == '__main__': main()