From d20a15fc08c22d6f67af292cf88e99e543a8c6cc Mon Sep 17 00:00:00 2001 From: Sergey Date: Thu, 2 Mar 2023 08:51:29 +0400 Subject: [PATCH] Logging refactoring (#4891) * move logging call into modules where actual logging is happening don't change settings of root logging initialize handlers when it becomes possible add colors to logs * rename logging module to sv_logging to avoid to confuse it with the build-in module * add separate logger for test logs * it's not always possible to have relative path * during registration of extension Blender text can be None --- __init__.py | 2 + core/__init__.py | 44 ++- core/handlers.py | 14 +- core/socket_data.py | 6 +- core/sockets.py | 1 - core/tasks.py | 6 +- core/update_system.py | 4 +- data_structure.py | 4 +- dependencies.py | 9 +- .../demo/turtle_random_walk.py | 7 +- .../SNLite_templates/demo/turtle_spiral.py | 8 +- .../SNLite_templates/demo/voronoi_scipy_3d.py | 9 +- .../utils/spherical_voronoi_3d_scipy.py | 8 +- node_tree.py | 69 ++--- nodes/curve/curve_lerp.py | 5 +- nodes/curve/extremes.py | 2 +- nodes/curve/interpolate_nurbs_curve.py | 6 +- nodes/curve/intersect_curves.py | 2 +- nodes/curve/nearest_point.py | 2 +- nodes/curve/reduce_degree.py | 2 +- nodes/curve/tangent_curve.py | 2 +- nodes/exchange/FCStd_read.py | 8 +- nodes/exchange/FCStd_read_mod.py | 6 +- nodes/exchange/FCStd_sketch.py | 6 +- nodes/exchange/FCStd_spreadsheet.py | 8 +- nodes/exchange/FCStd_write.py | 4 +- nodes/field/coordinate_scalar_field.py | 6 +- nodes/field/field_bend_along_surface.py | 9 +- nodes/field/image_field.py | 8 +- nodes/field/merge_scalar_fields.py | 7 +- nodes/field/mesh_normal_field.py | 5 +- nodes/field/noise_vfield.py | 7 +- nodes/field/scalar_field_curvature.py | 6 +- nodes/field/scalar_field_curve_map.py | 6 +- nodes/field/scalar_field_eval.py | 8 +- nodes/field/vector_field_apply.py | 4 +- nodes/field/vector_field_eval.py | 4 +- nodes/field/vector_field_lines.py | 4 +- nodes/list_struct/levels.py | 4 +- nodes/logic/range_switch.py | 6 +- nodes/object_nodes/assign_materials.py | 9 +- nodes/scene/get_objects_data.py | 3 +- nodes/scene/timer.py | 64 ++-- nodes/script/formula_interpolate.py | 4 +- nodes/script/mesh_eval.py | 6 +- nodes/script/profile_mk3.py | 8 +- nodes/solid/export_solid.py | 6 +- nodes/surface/adaptive_tessellate.py | 7 +- nodes/surface/flip_surface.py | 5 +- nodes/surface/nurbs_loft.py | 2 +- nodes/surface/revolution_surface.py | 2 +- nodes/surface/ruled_surface.py | 4 +- nodes/surface/subdomain.py | 4 +- nodes/surface/surface_bevel_curve.py | 1 - nodes/surface/surface_lerp.py | 4 +- nodes/surface/surface_reduce_degree.py | 2 +- nodes/surface/surface_reparametrize.py | 3 +- nodes/surface/swap.py | 6 +- nodes/surface/taper_sweep.py | 2 +- nodes/surface/tessellate_trim.py | 5 +- nodes/viz/mesh_viewer.py | 2 +- old_nodes/__init__.py | 6 +- old_nodes/formula3.py | 2 +- old_nodes/levels.py | 6 +- old_nodes/mesh_select.py | 11 +- old_nodes/remove_doubles.py | 6 +- settings.py | 9 +- tests/bezier_tests.py | 2 +- tests/core_tests.py | 5 +- tests/cubic_spline_tests.py | 3 +- tests/curve_tests.py | 6 +- tests/data_structure_tests.py | 7 +- tests/diameter_tests.py | 3 +- tests/dict_tests.py | 4 +- tests/docs_tests.py | 1 - tests/formula_interpolate_tests.py | 8 +- tests/general_fuse_tests.py | 2 - tests/geom_tests.py | 6 +- tests/init_tests.py | 9 +- tests/issue_4469_tests.py | 2 - tests/issue_4757_tests.py | 15 +- tests/json_import_simple_tests.py | 3 +- tests/json_import_tests.py | 4 +- tests/linear_approximation_tests.py | 1 - tests/linear_spline_tests.py | 2 +- tests/math_tests.py | 4 +- tests/nurbs_tests.py | 2 +- tests/profile_mk3_tests.py | 9 +- tests/simple_generator_tests.py | 2 +- tests/simple_viewer_text_tests.py | 3 +- tests/socket_conversion_tests.py | 11 +- tests/ui_tests.py | 10 +- ui/bgl_callback_nodeview.py | 6 +- ui/color_def.py | 4 +- ui/nodes_replacement.py | 5 +- ui/nodeview_space_menu.py | 8 +- ui/presets.py | 68 ++--- ui/profile_panel.py | 6 +- ui/sv_IO_panel.py | 20 +- ui/sv_extra_search.py | 4 +- ui/sv_panel_display_nodes.py | 62 ++-- ui/testing_panel.py | 4 +- ui/text_editor_plugins.py | 4 +- utils/adaptive_curve.py | 12 +- utils/adaptive_surface.py | 17 +- utils/apidoc.py | 4 +- utils/ascii_print.py | 1 - utils/curve/algorithms.py | 4 +- utils/curve/bakery.py | 6 +- utils/curve/core.py | 10 +- utils/curve/freecad.py | 4 +- utils/curve/nurbs.py | 11 +- utils/curve/nurbs_algorithms.py | 8 +- utils/curve/nurbs_solver.py | 4 +- utils/decorators.py | 4 +- utils/field/probe.py | 5 +- utils/geom.py | 18 +- utils/logging.py | 279 ------------------ utils/manifolds.py | 14 +- utils/modules/eval_formula.py | 4 +- utils/modules/matrix_utils.py | 2 +- utils/modules/profile_mk3/interpreter.py | 11 +- utils/modules/profile_mk3/parser.py | 4 +- utils/profile.py | 14 +- utils/quad_grid.py | 3 - utils/surface/algorithms.py | 10 +- utils/surface/coons.py | 5 +- utils/surface/core.py | 6 +- utils/surface/gordon.py | 21 +- utils/surface/nurbs.py | 14 +- utils/surface/populate.py | 7 +- utils/surface/primitives.py | 2 +- utils/sv_IO_panel_tools.py | 12 +- utils/sv_batch_primitives.py | 4 +- utils/sv_bmesh_utils.py | 14 +- utils/sv_gist_tools.py | 9 +- utils/sv_json_import.py | 10 +- utils/sv_logging.py | 225 ++++++++++++++ utils/testing.py | 65 ++-- utils/turtle.py | 15 +- utils/voronoi.py | 6 +- 141 files changed, 788 insertions(+), 908 deletions(-) delete mode 100644 utils/logging.py create mode 100644 utils/sv_logging.py diff --git a/__init__.py b/__init__.py index 189b98b2a9..1a736a5d06 100755 --- a/__init__.py +++ b/__init__.py @@ -117,6 +117,7 @@ def import_sverchok(): def register(): from sverchok.utils import ascii_print core.sv_register_modules(imported_modules) + core.enable_logging() core.sv_register_modules(core.imported_utils_modules()) core.sv_register_modules(node_modules) ascii_print.show_welcome() @@ -126,5 +127,6 @@ def unregister(): core.sv_unregister_modules(imported_modules) core.sv_unregister_modules(core.imported_utils_modules()) core.sv_unregister_modules(node_modules) + core.disable_logging() # EOF diff --git a/core/__init__.py b/core/__init__.py index c248806494..360580ab24 100644 --- a/core/__init__.py +++ b/core/__init__.py @@ -1,6 +1,10 @@ import importlib +import logging import sys - +import sverchok +import bpy +from sverchok.utils.development import get_version_string +from sverchok.utils.sv_logging import add_file_handler, remove_console_handler root_modules = [ "dependencies", @@ -84,6 +88,13 @@ def import_settings(imported_modules): imported_modules.append(settings) +def import_logging(imported_modules): + """Should be registered second after add-on settings""" + module = importlib.import_module(".sv_logging", "sverchok.utils") + # the module will be in imported_utils_modules - move sv_logging to core? + # imported_modules.append(module) + + def import_all_modules(imported_modules, mods_bases): for mods, base in mods_bases: import_modules(mods, base, imported_modules) @@ -113,10 +124,41 @@ def init_architecture(): # print('sv: import settings') import_settings(imported_modules) # print('sv: import all modules') + import_logging(imported_modules) import_all_modules(imported_modules, mods_bases) return imported_modules +def enable_logging(): + """Should be called after registration the add-on settings. + Adds additional handlers according the add-on settings and set logging level""" + if sverchok.reload_event: + return + + addon = bpy.context.preferences.addons.get(sverchok.__name__) + prefs = addon.preferences + + sv_logger = logging.getLogger('sverchok') + level = getattr(logging, prefs.log_level) + sv_logger.setLevel(level) + if prefs.log_to_file: + add_file_handler(prefs.log_file_name) + if not prefs.log_to_console: + remove_console_handler() + + logging.captureWarnings(True) + sv_logger.info(f'Initializing Sverchok logging (level={prefs.log_level}). ' + f'Blender version={bpy.app.version_string},' + f' Sverchok version={get_version_string()}') + + +def disable_logging(): + sv_logger = logging.getLogger('sverchok') + for handler in sv_logger.handlers[:]: + handler.close() + sv_logger.removeHandler(handler) + + def interupted_activation_detected(): activation_message = """\n ** Sverchok needs a couple of seconds to become activated when you enable it for the first time. ** diff --git a/core/handlers.py b/core/handlers.py index c0c376a621..c9ee081fc7 100644 --- a/core/handlers.py +++ b/core/handlers.py @@ -1,16 +1,16 @@ import bpy from bpy.app.handlers import persistent +import sverchok from sverchok import old_nodes from sverchok import data_structure import sverchok.core.events as ev import sverchok.core.tasks as ts -import sverchok.utils.logging as log from sverchok.core.event_system import handle_event from sverchok.core.socket_data import clear_all_socket_cache from sverchok.ui import bgl_callback_nodeview, bgl_callback_3dview from sverchok.utils.handle_blender_data import BlTrees -from sverchok.utils.logging import catch_log_error, debug +from sverchok.utils.sv_logging import catch_log_error, TextBufferHandler, sv_logger import sverchok.settings as settings _state = {'frame': None} @@ -59,7 +59,7 @@ def sv_handler_undo_post(scene): num_to_test_against += len(ng.nodes) if undo_handler_node_count['sv_groups'] != num_to_test_against: - debug('looks like a node was removed, cleaning') + sv_logger.debug('looks like a node was removed, cleaning') sv_clean(scene) undo_handler_node_count['sv_groups'] = 0 @@ -154,6 +154,7 @@ def sv_post_load(scene): post_load handler is also called when Blender is first ran The method should initialize Sverchok parts which are required by loaded tree """ + TextBufferHandler.add_to_main_logger() from sverchok import node_tree, settings # ensure current nodeview view scale / location parameters reflect users' system settings @@ -197,7 +198,12 @@ def update_frame_change_mode(): @persistent def save_pre_handler(scene): - log.clear_internal_buffer() + addon = bpy.context.preferences.addons.get(sverchok.__name__) + prefs = addon.preferences + if prefs.log_to_buffer_clean: + for handler in sv_logger.handlers: + if hasattr(handler, 'clear'): + handler.clear() handler_dict = { diff --git a/core/socket_data.py b/core/socket_data.py index e0ed72a7a6..792c1bb789 100644 --- a/core/socket_data.py +++ b/core/socket_data.py @@ -17,7 +17,7 @@ # ##### END GPL LICENSE BLOCK ##### """For internal usage of the sockets module""" - +import logging from collections import UserDict from itertools import chain from traceback import format_list, extract_stack @@ -25,11 +25,11 @@ from bpy.types import NodeSocket from sverchok.core.sv_custom_exceptions import SvNoDataError -from sverchok.utils.logging import debug from sverchok.utils.handle_blender_data import BlTrees SockId = NewType('SockId', str) +sv_logger = logging.getLogger('sverchok') class DebugMemory(UserDict): @@ -112,7 +112,7 @@ def _update_sockets(self): continue if sock.socket_id in self._id_sock: ds = self._id_sock[sock.socket_id] - debug(f"SOCKET ID DUPLICATION: " + sv_logger.debug(f"SOCKET ID DUPLICATION: " f"1 - {ds.id_data.name} {ds.node.name=} {ds.name=}" f"2 - {sock.id_data.name} {node.name=} {sock.name=}") self._id_sock[sock.socket_id] = sock diff --git a/core/sockets.py b/core/sockets.py index adbbc3aa63..fb0ca5fd53 100644 --- a/core/sockets.py +++ b/core/sockets.py @@ -46,7 +46,6 @@ from sverchok.utils.curve.algorithms import reparametrize_curve from sverchok.utils.surface import SvSurface -from sverchok.utils.logging import warning from sverchok.dependencies import FreeCAD STANDARD_TYPES = SIMPLE_DATA_TYPES + (SvCurve, SvSurface) diff --git a/core/tasks.py b/core/tasks.py index 7e339b2e77..f8786e8daa 100644 --- a/core/tasks.py +++ b/core/tasks.py @@ -6,7 +6,7 @@ import bpy from sverchok.data_structure import post_load_call from sverchok.core.sv_custom_exceptions import CancelError -from sverchok.utils.logging import catch_log_error, debug +from sverchok.utils.sv_logging import catch_log_error, sv_logger from sverchok.utils.profile import profile from sverchok.utils.handle_blender_data import BlTrees @@ -119,7 +119,7 @@ def _finish(self): t['SKIP_UPDATE'] = True gc.enable() - debug(f'Global update - {int((time() - self._start_time) * 1000)}ms') + sv_logger.debug(f'Global update - {int((time() - self._start_time) * 1000)}ms') del self._start_time @cached_property @@ -143,7 +143,7 @@ def _main_area(self) -> Optional: return area except ReferenceError: # probably all reports should be cleaned through search - debug(f"Unable report a nodes updating progress") + sv_logger.debug(f"Unable report a nodes updating progress") def _report_progress(self, text: str = None): """Show text in the tree editor header. If text is none the header diff --git a/core/update_system.py b/core/update_system.py index be9d5c9dbd..a15ac3cbed 100644 --- a/core/update_system.py +++ b/core/update_system.py @@ -12,7 +12,7 @@ from sverchok.core.sv_custom_exceptions import CancelError, SvNoDataError from sverchok.core.socket_conversions import conversions from sverchok.utils.profile import profile -from sverchok.utils.logging import log_error +from sverchok.utils.sv_logging import node_error_logger from sverchok.utils.tree_walk import bfs_walk if TYPE_CHECKING: @@ -699,7 +699,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): self._node[ERROR_KEY] = None self._node[TIME_KEY] = perf_counter() - self._start else: - log_error(exc_val) + node_error_logger.error(exc_val, exc_info=True) self._node[UPDATE_KEY] = False self._node[ERROR_KEY] = repr(exc_val) diff --git a/data_structure.py b/data_structure.py index f78a11c70a..a6fcdd1043 100755 --- a/data_structure.py +++ b/data_structure.py @@ -36,7 +36,7 @@ tile as np_tile, float64, int32, int64) -from sverchok.utils.logging import debug +from sverchok.utils.sv_logging import sv_logger import numpy as np @@ -1255,7 +1255,7 @@ def changable_sockets(node, inputsocketname, outputsocketname): if not inputsocketname in node.inputs: # - node not initialized in sv_init yet, # - or socketname incorrect - debug(f"changable_socket was called on {node.name} with a socket named {inputsocketname}, this socket does not exist") + sv_logger.debug(f"changable_socket was called on {node.name} with a socket named {inputsocketname}, this socket does not exist") return in_socket = node.inputs[inputsocketname] diff --git a/dependencies.py b/dependencies.py index 9970b06272..b65cd9173f 100644 --- a/dependencies.py +++ b/dependencies.py @@ -23,11 +23,14 @@ todo: Create dependencies.txt file and import modules from there """ +import logging -from sverchok.utils.logging import info, debug import sverchok.settings as settings +logger = logging.getLogger('sverchok') + + class SvDependency(): """ Definition of external dependency package. @@ -186,6 +189,6 @@ def register(): good_names = [d.package for d in sv_dependencies.values() if d.module is not None and d.package is not None] if good_names: - info("Dependencies available: %s.", ", ".join(good_names)) + logger.info("Dependencies available: %s.", ", ".join(good_names)) else: - info("No dependencies are available.") + logger.info("No dependencies are available.") diff --git a/node_scripts/SNLite_templates/demo/turtle_random_walk.py b/node_scripts/SNLite_templates/demo/turtle_random_walk.py index 45e75f17bd..94f5817e8d 100644 --- a/node_scripts/SNLite_templates/demo/turtle_random_walk.py +++ b/node_scripts/SNLite_templates/demo/turtle_random_walk.py @@ -9,14 +9,15 @@ out out_face_mask s out out_face_data s """ - +import logging import random from sverchok.data_structure import zip_long_repeat from sverchok.utils.sv_bmesh_utils import bmesh_from_pydata -from sverchok.utils.logging import debug, info from sverchok.utils.turtle import Turtle +logger = logging.getLogger('sverchok') + if in_select_mask is None: in_select_mask = [[]] if in_paint_mask is None: @@ -27,7 +28,7 @@ objects = zip_long_repeat(in_verts, in_faces, in_start_face_idx, in_steps, in_select_mask, in_paint_mask, in_seed) for verts, faces, start_face, steps, select_mask, paint_mask, seed in objects: - info(seed) + logger.info(seed) if isinstance(seed, (list, tuple)): seed = seed[0] random.seed(seed) diff --git a/node_scripts/SNLite_templates/demo/turtle_spiral.py b/node_scripts/SNLite_templates/demo/turtle_spiral.py index 10946bb6ed..a696b9eadd 100644 --- a/node_scripts/SNLite_templates/demo/turtle_spiral.py +++ b/node_scripts/SNLite_templates/demo/turtle_spiral.py @@ -8,18 +8,20 @@ out out_face_mask s out out_face_data s """ +import logging from sverchok.data_structure import zip_long_repeat from sverchok.utils.sv_bmesh_utils import bmesh_from_pydata -from sverchok.utils.logging import info, debug from sverchok.utils.turtle import Turtle +logger = logging.getLogger('sverchok') + if in_select_mask is None: in_select_mask = [[]] if in_paint_mask is None: in_paint_mask = [[]] -info(in_start_face_idx) +logger.info(in_start_face_idx) out_face_mask = [] out_face_data = [] @@ -54,7 +56,7 @@ for i in range(turns * 2): steps = (i+1)*2 - debug("Steps := %s", steps) + logger.debug("Steps := %s", steps) turtle.step(steps) turtle.turn_prev() turtle.step(steps) diff --git a/node_scripts/SNLite_templates/demo/voronoi_scipy_3d.py b/node_scripts/SNLite_templates/demo/voronoi_scipy_3d.py index bd7bbdd794..dd8b9c8b2c 100644 --- a/node_scripts/SNLite_templates/demo/voronoi_scipy_3d.py +++ b/node_scripts/SNLite_templates/demo/voronoi_scipy_3d.py @@ -3,18 +3,15 @@ out out_verts v out out_faces s """ +import logging -import numpy as np -import sys - -from sverchok.utils.logging import exception, info -from sverchok.data_structure import zip_long_repeat +logger = logging.getLogger('sverchok') try: import scipy from scipy.spatial import Voronoi except ImportError as e: - info("SciPy module is not available. Please refer to https://github.com/nortikin/sverchok/wiki/Non-standard-Python-modules-installation for how to install it.") + logger.info("SciPy module is not available. Please refer to https://github.com/nortikin/sverchok/wiki/Non-standard-Python-modules-installation for how to install it.") raise e out_verts = [] diff --git a/node_scripts/SNLite_templates/utils/spherical_voronoi_3d_scipy.py b/node_scripts/SNLite_templates/utils/spherical_voronoi_3d_scipy.py index d130adac8e..5fef07051c 100644 --- a/node_scripts/SNLite_templates/utils/spherical_voronoi_3d_scipy.py +++ b/node_scripts/SNLite_templates/utils/spherical_voronoi_3d_scipy.py @@ -5,19 +5,21 @@ out out_verts v out out_faces s """ +import logging import numpy as np import sys -from sverchok.utils.logging import exception, info from sverchok.data_structure import zip_long_repeat from sverchok.utils.math import to_spherical, from_spherical +logger = logging.getLogger('sverchok') + try: import scipy from scipy.spatial import SphericalVoronoi except ImportError as e: - info("SciPy module is not available. Please refer to https://github.com/nortikin/sverchok/wiki/Non-standard-Python-modules-installation for how to install it.") + logger.info("SciPy module is not available. Please refer to https://github.com/nortikin/sverchok/wiki/Non-standard-Python-modules-installation for how to install it.") raise e def to_radius(r, v, c): @@ -36,7 +38,7 @@ def to_radius(r, v, c): if isinstance(radius, (list, tuple)): radius = radius[0] center = center[0] - #info("Center: %s, radius: %s", center, radius) + # logger.info("Center: %s, radius: %s", center, radius) points = np.array([to_radius(radius, v, center) for v in points]) vor = SphericalVoronoi(points, radius=radius, center=np.array(center)) diff --git a/node_tree.py b/node_tree.py index 2052b97564..54a53370d4 100644 --- a/node_tree.py +++ b/node_tree.py @@ -25,7 +25,7 @@ """ -import inspect +import logging import sys import time from contextlib import contextmanager @@ -44,8 +44,7 @@ from sverchok.data_structure import classproperty, post_load_call from sverchok.utils.sv_node_utils import recursive_framed_location_finder from sverchok.utils.docstring import SvDocstring -import sverchok.utils.logging -from sverchok.utils.logging import debug, catch_log_error, is_enabled_for +from sverchok.utils.sv_logging import catch_log_error, sv_logger from sverchok.ui import color_def from sverchok.ui.nodes_replacement import set_inputs_mapping, set_outputs_mapping @@ -85,13 +84,13 @@ def update_gl_scale_info(self, origin=None): this is instead of calling `get_dpi_factor` on every redraw. """ - debug(f"update_gl_scale_info called from {origin or self.name}") + sv_logger.debug(f"update_gl_scale_info called from {origin or self.name}") try: from sverchok.utils.context_managers import sv_preferences with sv_preferences() as prefs: prefs.set_nodeview_render_params(None) except Exception as err: - debug('failed to get gl scale info', err) + sv_logger.debug('failed to get gl scale info', err) @contextmanager def init_tree(self): @@ -490,42 +489,30 @@ class NodeUtils: Most of them have nothing related with nodes and using as aliases of some functionality. The class can be surely ignored during creating of new nodes. """ - def get_logger(self): - if hasattr(self, "draw_label"): - name = self.draw_label() - else: - name = self.label - if not name: - name = self.bl_label - if not name: - name = self.__class__.__name__ - - # add information about the module location - frame, _, line, *_ = inspect.stack()[2] - module = inspect.getmodule(frame) - module_name = module.__name__ if module is not None else '' - name = f'{module_name} {line} ({name})' - return sverchok.utils.logging.getLogger(name) - - def debug(self, msg, *args, **kwargs): - if is_enabled_for('DEBUG'): - self.get_logger().debug(msg, *args, **kwargs) - - def info(self, msg, *args, **kwargs): - if is_enabled_for('INFO'): - self.get_logger().info(msg, *args, **kwargs) - - def warning(self, msg, *args, **kwargs): - if is_enabled_for('WARNING'): - self.get_logger().warning(msg, *args, **kwargs) - - def error(self, msg, *args, **kwargs): - if is_enabled_for('ERROR'): - self.get_logger().error(msg, *args, **kwargs) - - def exception(self, msg, *args, **kwargs): - if is_enabled_for('EXCEPTION'): - self.get_logger().exception(msg, *args, **kwargs) + @property + def sv_logger(self): + # todo inject node label into records? + return logging.getLogger('sverchok.nodes') + + @property + def debug(self): + return self.sv_logger.debug + + @property + def info(self): + return self.sv_logger.info + + @property + def warning(self): + return self.sv_logger.warning + + @property + def error(self): + return self.sv_logger.error + + @property + def exception(self): + return self.sv_logger.exception def wrapper_tracked_ui_draw_op(self, layout_element, operator_idname, **keywords): """ diff --git a/nodes/curve/curve_lerp.py b/nodes/curve/curve_lerp.py index 209b48fab8..c5a472f3fd 100644 --- a/nodes/curve/curve_lerp.py +++ b/nodes/curve/curve_lerp.py @@ -1,14 +1,11 @@ - -import numpy as np - import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception from sverchok.utils.curve import SvCurve, SvCurveLerpCurve + class SvCurveLerpCurveNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Curve Lerp diff --git a/nodes/curve/extremes.py b/nodes/curve/extremes.py index 5dd4613443..422e5dcd9c 100644 --- a/nodes/curve/extremes.py +++ b/nodes/curve/extremes.py @@ -87,7 +87,7 @@ def process(self): new_t = [] new_points = [] for curve, field, samples in zip_long_repeat(curves, fields, samples_i): - ts = curve_extremes(curve, field, samples, self.direction, self.on_fail, self.get_logger()) + ts = curve_extremes(curve, field, samples, self.direction, self.on_fail, self.sv_logger) ps = curve.evaluate_array(np.array(ts)).tolist() new_t.extend(ts) new_points.extend(ps) diff --git a/nodes/curve/interpolate_nurbs_curve.py b/nodes/curve/interpolate_nurbs_curve.py index b6792d14aa..6fba0f5ef9 100644 --- a/nodes/curve/interpolate_nurbs_curve.py +++ b/nodes/curve/interpolate_nurbs_curve.py @@ -6,12 +6,12 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat -from sverchok.utils.logging import info, exception -from sverchok.utils.curve.nurbs import SvNurbsCurve, SvNativeNurbsCurve, SvGeomdlCurve +from sverchok.utils.curve.nurbs import SvNurbsCurve from sverchok.utils.nurbs_common import SvNurbsMaths from sverchok.utils.math import supported_metrics from sverchok.dependencies import geomdl + class SvExInterpolateNurbsCurveNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: NURBS Curve interpolation @@ -90,7 +90,7 @@ def process(self): implementation = SvNurbsCurve.NATIVE metric = self.metric - curve = SvNurbsMaths.interpolate_curve(implementation, degree, vertices, metric=metric, cyclic=self.cyclic, logger=self.get_logger()) + curve = SvNurbsMaths.interpolate_curve(implementation, degree, vertices, metric=metric, cyclic=self.cyclic, logger=self.sv_logger) points_out.append(curve.get_control_points().tolist()) knots_out.append(curve.get_knotvector().tolist()) diff --git a/nodes/curve/intersect_curves.py b/nodes/curve/intersect_curves.py index db209c6386..0d6f7f0e58 100644 --- a/nodes/curve/intersect_curves.py +++ b/nodes/curve/intersect_curves.py @@ -133,7 +133,7 @@ def process_native(self, curve1, curve2): res = intersect_nurbs_curves(curve1, curve2, method = self.method, numeric_precision = self.precision, - logger = self.get_logger()) + logger = self.sv_logger) points = [(r[0], r[1], r[2].tolist()) for r in res] return self._filter(points) diff --git a/nodes/curve/nearest_point.py b/nodes/curve/nearest_point.py index e719a792aa..3e86642bc5 100644 --- a/nodes/curve/nearest_point.py +++ b/nodes/curve/nearest_point.py @@ -79,7 +79,7 @@ def process(self): samples=self.samples, precise=self.precise, output_points = need_points, method = self.method, - logger = self.get_logger()) + logger = self.sv_logger) if need_points: new_t = [r[0] for r in results] new_points = [r[1].tolist() for r in results] diff --git a/nodes/curve/reduce_degree.py b/nodes/curve/reduce_degree.py index 767f6500d4..84134e7e1f 100644 --- a/nodes/curve/reduce_degree.py +++ b/nodes/curve/reduce_degree.py @@ -98,7 +98,7 @@ def process(self): kwargs = dict(target = degree) curve = curve.reduce_degree(tolerance=tolerance, if_possible = self.if_possible, - logger = self.get_logger(), + logger = self.sv_logger, **kwargs) new_curves.append(curve) if flat_output: diff --git a/nodes/curve/tangent_curve.py b/nodes/curve/tangent_curve.py index 8e6653178e..94c504c95a 100644 --- a/nodes/curve/tangent_curve.py +++ b/nodes/curve/tangent_curve.py @@ -100,7 +100,7 @@ def process(self): points, tangents, metric = self.metric, cyclic = self.cyclic, - logger = self.get_logger()) + logger = self.sv_logger) new_controls = new_curve.get_control_points().tolist() curves_i.append(new_curve) controls_i.append(new_controls) diff --git a/nodes/exchange/FCStd_read.py b/nodes/exchange/FCStd_read.py index feefb32b1f..3f1b34aa9d 100644 --- a/nodes/exchange/FCStd_read.py +++ b/nodes/exchange/FCStd_read.py @@ -3,7 +3,7 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger from sverchok.dependencies import FreeCAD from sverchok.utils.sv_operator_mixins import SvGenericNodeLocator @@ -161,8 +161,8 @@ def LabelReader(self,context): labels.append( (obj.Label, obj.Label, obj.Label) ) except Exception as err: - info(f'FCStd label read error: {Fname=}') - info(err) + sv_logger.info(f'FCStd label read error: {Fname=}') + sv_logger.info(err) finally: # del doc F.closeDocument(doc.Name) @@ -223,7 +223,7 @@ def LoadSolid(fc_file, part_filter, obj_mask, tool_parts, inv_filter): solids.add((obj.Shape, (obj.FullName, obj.Name, obj.Label))) except: - info('FCStd read error') + sv_logger.info('FCStd read error') finally: # del doc F.closeDocument(doc.Name) diff --git a/nodes/exchange/FCStd_read_mod.py b/nodes/exchange/FCStd_read_mod.py index 54fb75038e..17cb852f8d 100644 --- a/nodes/exchange/FCStd_read_mod.py +++ b/nodes/exchange/FCStd_read_mod.py @@ -3,7 +3,7 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger from sverchok.dependencies import FreeCAD from sverchok.utils.sv_operator_mixins import SvGenericNodeLocator @@ -56,7 +56,7 @@ def LabelReader(operator): if obj.Module in module_filter or obj.TypeId in module_filter: labels.append( (obj.Label, obj.Label, obj.Label) ) except: - info('FCStd label read error') + sv_logger.info('FCStd label read error') finally: #del doc F.closeDocument(doc.Name) @@ -312,7 +312,7 @@ def LoadSolid( solids.add(( obj.Shape, obj_info )) except Exception as err: - info(f"FCStd read error {err}") + sv_logger.info(f"FCStd read error {err}") finally: #del doc diff --git a/nodes/exchange/FCStd_sketch.py b/nodes/exchange/FCStd_sketch.py index 0bd3160a27..34179842db 100644 --- a/nodes/exchange/FCStd_sketch.py +++ b/nodes/exchange/FCStd_sketch.py @@ -5,7 +5,7 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger from sverchok.dependencies import FreeCAD from sverchok.utils.sv_operator_mixins import SvGenericNodeLocator @@ -149,7 +149,7 @@ def LabelReader(self,context): F.closeDocument(Fname) except: - info('FCStd read error') + sv_logger.info('FCStd read error') return labels @@ -188,7 +188,7 @@ def LoadSketch(fc_file, sketch_filter, max_points, inv_filter, read_mode): F.setActiveDocument(Fname) except: - info('FCStd read error') + sv_logger.info('FCStd read error') return (Verts,Edges,Curves) #___________________SEARCH FOR SKETCHES diff --git a/nodes/exchange/FCStd_spreadsheet.py b/nodes/exchange/FCStd_spreadsheet.py index 90bd29394d..1f2d28a63e 100644 --- a/nodes/exchange/FCStd_spreadsheet.py +++ b/nodes/exchange/FCStd_spreadsheet.py @@ -3,7 +3,7 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger from sverchok.dependencies import FreeCAD from sverchok.utils.sv_operator_mixins import SvGenericNodeLocator @@ -133,7 +133,7 @@ def LabelReader(self,context): labels.append( (obj.Label, obj.Label, obj.Label) ) except: - info('LabelReader Spreadsheet error') + sv_logger.info('LabelReader Spreadsheet error') finally: F.closeDocument(Fname) @@ -190,7 +190,7 @@ def LabelReader(self,context): labels.append( (label, label, label) ) except: - info('Label reader read cell error') + sv_logger.info('Label reader read cell error') finally: F.closeDocument(Fname) @@ -245,7 +245,7 @@ def WriteParameter(fc_file,spreadsheet,alias,par_write,write): break except: - info('WriteParameter error') + sv_logger.info('WriteParameter error') finally: F.closeDocument(Fname) diff --git a/nodes/exchange/FCStd_write.py b/nodes/exchange/FCStd_write.py index 2877dca958..4a444934b0 100644 --- a/nodes/exchange/FCStd_write.py +++ b/nodes/exchange/FCStd_write.py @@ -3,7 +3,7 @@ from sverchok.node_tree import SverchCustomTreeNode # OLD throttled from sverchok.data_structure import updateNode, match_long_repeat # NEW throttle_and_update_node -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger from sverchok.dependencies import FreeCAD from sverchok.utils.sv_operator_mixins import SvGenericNodeLocator @@ -149,7 +149,7 @@ def fc_write_parts(fc_file, verts, faces, part_name, solid, mod): F.open(fc_file) except Exception as err: - info(f'FCStd open error, {err}') + sv_logger.info(f'FCStd open error, {err}') return F.setActiveDocument(Fname) diff --git a/nodes/field/coordinate_scalar_field.py b/nodes/field/coordinate_scalar_field.py index 2020f19135..f78c9ec01a 100644 --- a/nodes/field/coordinate_scalar_field.py +++ b/nodes/field/coordinate_scalar_field.py @@ -1,15 +1,13 @@ -import numpy as np - import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, StringProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, match_long_repeat -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode from sverchok.utils.field.scalar import SvCoordinateScalarField + class SvCoordScalarFieldNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Coordinate Scalar Field diff --git a/nodes/field/field_bend_along_surface.py b/nodes/field/field_bend_along_surface.py index 7169e662aa..308c281f08 100644 --- a/nodes/field/field_bend_along_surface.py +++ b/nodes/field/field_bend_along_surface.py @@ -1,15 +1,8 @@ - -from sverchok.utils.logging import info, exception - -import numpy as np -from math import sqrt - import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level -from sverchok.utils.geom import diameter +from sverchok.data_structure import updateNode, zip_long_repeat from sverchok.utils.field.vector import SvBendAlongSurfaceField diff --git a/nodes/field/image_field.py b/nodes/field/image_field.py index a9bdb19de6..0a8dba67d5 100644 --- a/nodes/field/image_field.py +++ b/nodes/field/image_field.py @@ -1,17 +1,13 @@ -import numpy as np - import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, StringProperty -from mathutils import kdtree -from mathutils import bvhtree from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode from sverchok.utils.field.image import load_image, SvImageScalarField, SvImageVectorField + class SvImageFieldNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Image Field diff --git a/nodes/field/merge_scalar_fields.py b/nodes/field/merge_scalar_fields.py index 344600c459..8375255e13 100644 --- a/nodes/field/merge_scalar_fields.py +++ b/nodes/field/merge_scalar_fields.py @@ -1,15 +1,12 @@ - -import numpy as np - import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, StringProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, match_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode from sverchok.utils.field.scalar import SvMergedScalarField, SvScalarField + class SvMergeScalarFieldsNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Merge / Join Scalar Fields diff --git a/nodes/field/mesh_normal_field.py b/nodes/field/mesh_normal_field.py index 09b65bbc56..9d9a43c6ea 100644 --- a/nodes/field/mesh_normal_field.py +++ b/nodes/field/mesh_normal_field.py @@ -12,10 +12,8 @@ from mathutils import bvhtree from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, match_long_repeat -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode, zip_long_repeat from sverchok.utils.sv_bmesh_utils import bmesh_from_pydata -from sverchok.utils.logging import info, exception from sverchok.utils.field.vector import SvBvhAttractorVectorField from sverchok.utils.field.rbf import SvBvhRbfNormalVectorField from sverchok.dependencies import scipy @@ -24,6 +22,7 @@ if scipy is not None: from scipy.interpolate import Rbf + class SvExMeshNormalFieldNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Mesh Normal Field diff --git a/nodes/field/noise_vfield.py b/nodes/field/noise_vfield.py index 75aa3b9cf5..78851f4911 100644 --- a/nodes/field/noise_vfield.py +++ b/nodes/field/noise_vfield.py @@ -1,19 +1,16 @@ -import numpy as np - import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, StringProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, match_long_repeat -from sverchok.utils.modules.eval_formula import get_variables, safe_eval -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode from sverchok.utils.sv_noise_utils import noise_options, PERLIN_ORIGINAL from sverchok.utils.field.vector import SvNoiseVectorField avail_noise = [(t[0], t[0].title(), t[0].title(), '', t[1]) for t in noise_options] + class SvNoiseVectorFieldNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Noise Vector Field diff --git a/nodes/field/scalar_field_curvature.py b/nodes/field/scalar_field_curvature.py index 77f86582a7..c5a03d96b9 100644 --- a/nodes/field/scalar_field_curvature.py +++ b/nodes/field/scalar_field_curvature.py @@ -1,15 +1,13 @@ -import numpy as np - import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, StringProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, match_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode, ensure_nesting_level from sverchok.utils.field.scalar import SvScalarField, SvScalarFieldGaussCurvature, SvScalarFieldMeanCurvature, SvScalarFieldPrincipalCurvature, ScalarFieldCurvatureCalculator + class SvScalarFieldCurvatureNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Scalar Field Curvature diff --git a/nodes/field/scalar_field_curve_map.py b/nodes/field/scalar_field_curve_map.py index e92fc429c0..12ef273330 100644 --- a/nodes/field/scalar_field_curve_map.py +++ b/nodes/field/scalar_field_curve_map.py @@ -1,17 +1,15 @@ -import numpy as np - import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, StringProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, match_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level from sverchok.utils.curve import SvCurve from sverchok.utils.field.scalar import SvScalarField from sverchok.utils.field.vector import SvScalarFieldCurveMap + class SvScalarFieldCurveMapNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Scalar Field Curve Map diff --git a/nodes/field/scalar_field_eval.py b/nodes/field/scalar_field_eval.py index bbf195b36f..c6b7f23d57 100644 --- a/nodes/field/scalar_field_eval.py +++ b/nodes/field/scalar_field_eval.py @@ -5,14 +5,10 @@ from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, StringProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level, match_long_repeat -from sverchok.utils.modules.eval_formula import get_variables, sv_compile, safe_eval_compiled -from sverchok.utils.logging import info, exception -from sverchok.utils.math import from_cylindrical, from_spherical, to_cylindrical, to_spherical - -from sverchok.utils.math import coordinate_modes +from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level from sverchok.utils.field.scalar import SvScalarField + class SvScalarFieldEvaluateNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Scalar Field Evaluate diff --git a/nodes/field/vector_field_apply.py b/nodes/field/vector_field_apply.py index fb56e0a9b4..faba624bc5 100644 --- a/nodes/field/vector_field_apply.py +++ b/nodes/field/vector_field_apply.py @@ -5,10 +5,10 @@ from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, StringProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, repeat_last_for_length, match_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode, zip_long_repeat, repeat_last_for_length, ensure_nesting_level from sverchok.utils.field.vector import SvVectorField + class SvVectorFieldApplyNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Vector Field Apply diff --git a/nodes/field/vector_field_eval.py b/nodes/field/vector_field_eval.py index 244da8e523..134e749c74 100644 --- a/nodes/field/vector_field_eval.py +++ b/nodes/field/vector_field_eval.py @@ -5,8 +5,8 @@ from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, StringProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, match_long_repeat -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode, zip_long_repeat + class SvVectorFieldEvaluateNode(SverchCustomTreeNode, bpy.types.Node): """ diff --git a/nodes/field/vector_field_lines.py b/nodes/field/vector_field_lines.py index 7738d34cfb..7809625b88 100644 --- a/nodes/field/vector_field_lines.py +++ b/nodes/field/vector_field_lines.py @@ -5,10 +5,10 @@ from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, StringProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, repeat_last_for_length, match_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level from sverchok.utils.mesh_functions import mesh_join + class SvVectorFieldLinesNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Vector Field Lines diff --git a/nodes/list_struct/levels.py b/nodes/list_struct/levels.py index f8408bf42e..1985c899b4 100644 --- a/nodes/list_struct/levels.py +++ b/nodes/list_struct/levels.py @@ -25,7 +25,7 @@ from sverchok.utils.curve.core import SvCurve from sverchok.utils.surface.core import SvSurface from sverchok.dependencies import FreeCAD -from sverchok.utils.logging import debug +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.handle_blender_data import correct_collection_length ALL_TYPES = SIMPLE_DATA_TYPES + (SvCurve, SvSurface) @@ -39,7 +39,7 @@ def update_entry(self, context): if hasattr(context, 'node'): updateNode(context.node, context) else: - debug("Node is not defined in this context, so will not update the node.") + sv_logger.debug("Node is not defined in this context, so will not update the node.") description : StringProperty(options = {'SKIP_SAVE'}, default="?") flatten : BoolProperty( diff --git a/nodes/logic/range_switch.py b/nodes/logic/range_switch.py index 5ad2717c54..e55c060d30 100644 --- a/nodes/logic/range_switch.py +++ b/nodes/logic/range_switch.py @@ -21,7 +21,7 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, match_long_repeat -from sverchok.utils.logging import debug + MODE_INSIDE_ON = "INSIDE ON" MODE_INSIDE_OFF = "INSIDE OFF" @@ -200,12 +200,12 @@ def process(self): if old_switch_count != new_switch_count: if new_switch_count > old_switch_count: # add new switches for n in range(old_switch_count, new_switch_count): - debug("creating new switch") + self.debug("creating new switch") switch = self.switches.add() else: # remove old switches while len(self.switches) > new_switch_count: n = len(self.switches) - 1 - debug("removing old switch") + self.debug("removing old switch") self.switches.remove(n) # update switches diff --git a/nodes/object_nodes/assign_materials.py b/nodes/object_nodes/assign_materials.py index 8508eb8d68..31f5bc141b 100644 --- a/nodes/object_nodes/assign_materials.py +++ b/nodes/object_nodes/assign_materials.py @@ -16,15 +16,14 @@ # # ##### END GPL LICENSE BLOCK ##### -import numpy as np - import bpy from bpy.props import StringProperty, IntProperty, CollectionProperty, PointerProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, match_long_repeat -from sverchok.utils.logging import info, debug +from sverchok.data_structure import updateNode +from sverchok.utils.sv_logging import sv_logger + class SvMaterialEntry(bpy.types.PropertyGroup): @@ -32,7 +31,7 @@ def update_material(self, context): if hasattr(context, 'node'): updateNode(context.node, context) else: - info("Node is not defined in this context, so will not update the node.") + sv_logger.info("Node is not defined in this context, so will not update the node.") material : PointerProperty(type = bpy.types.Material, update=update_material) diff --git a/nodes/scene/get_objects_data.py b/nodes/scene/get_objects_data.py index 978a505fe9..abb29551b3 100644 --- a/nodes/scene/get_objects_data.py +++ b/nodes/scene/get_objects_data.py @@ -17,7 +17,6 @@ from sverchok.utils.blender_mesh import ( read_verts, read_edges, read_verts_normal, read_face_normal, read_face_center, read_face_area, read_materials_idx) -from sverchok.utils.logging import debug class SvOB3BDataCollection(bpy.types.PropertyGroup): @@ -360,7 +359,7 @@ def process(self): except Exception as err: # it's not clear which cases this try catch should handle # probably it should skip wrong object types - debug('failure in process between frozen area', self.name, err) + self.debug('failure in process between frozen area', self.name, err) if o_ms: ms.append(mtrx) diff --git a/nodes/scene/timer.py b/nodes/scene/timer.py index d70ed6c238..746add19ac 100644 --- a/nodes/scene/timer.py +++ b/nodes/scene/timer.py @@ -22,7 +22,7 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, match_long_repeat from sverchok.utils.modules.statistics_functions import * -from sverchok.utils.logging import debug +from sverchok.utils.sv_logging import sv_logger TIMER_STATUS_STOPPED = "STOPPED" TIMER_STATUS_STARTED = "STARTED" @@ -120,16 +120,16 @@ def loop_count(self): return self.timer_loop_count def stop(self): - debug("* Timer {0}: STOP".format(self.timer_id)) + sv_logger.debug("* Timer {0}: STOP".format(self.timer_id)) self.timer_time = 0 self.timer_loop_count = 0 self.timer_status = TIMER_STATUS_STOPPED self.last_timer_status = TIMER_STATUS_STOPPED def start(self): - debug("* Timer {0}: START".format(self.timer_id)) + sv_logger.debug("* Timer {0}: START".format(self.timer_id)) if self.timer_status in [TIMER_STATUS_STOPPED, TIMER_STATUS_EXPIRED]: - debug("starting from zero") + sv_logger.debug("starting from zero") self.timer_time = 0 self.timer_start_frame = bpy.context.scene.frame_current self.timer_loop_count = 0 @@ -137,24 +137,24 @@ def start(self): self.last_timer_status = TIMER_STATUS_STARTED def pause(self): - debug("* Timer {0}: PAUSE".format(self.timer_id)) + sv_logger.debug("* Timer {0}: PAUSE".format(self.timer_id)) if self.timer_status == TIMER_STATUS_STARTED: self.timer_status = TIMER_STATUS_PAUSED def reset(self): - debug("* Timer {0}: RESET".format(self.timer_id)) + sv_logger.debug("* Timer {0}: RESET".format(self.timer_id)) self.timer_status = TIMER_STATUS_STOPPED self.timer_time = 0 self.timer_loop_count = 0 def expire(self): - debug("* Timer {0}: EXPIRE".format(self.timer_id)) + sv_logger.debug("* Timer {0}: EXPIRE".format(self.timer_id)) self.timer_status = TIMER_STATUS_EXPIRED self.timer_time = self.timer_duration self.timer_loop_count = self.timer_loops def loop_backward(self): - debug("* Timer {0}: LOOP BACKWARD".format(self.timer_id)) + sv_logger.debug("* Timer {0}: LOOP BACKWARD".format(self.timer_id)) if self.timer_loop_count == 0: # first loop ? self.last_timer_status = self.timer_status self.timer_status = TIMER_STATUS_STOPPED @@ -170,7 +170,7 @@ def loop_backward(self): self.timer_loop_count -= 1 def loop_forward(self): - debug("* Timer {0}: LOOP FORWARD".format(self.timer_id)) + sv_logger.debug("* Timer {0}: LOOP FORWARD".format(self.timer_id)) if self.timer_loop_count == self.timer_loops: # last loop ? self.last_timer_status = self.timer_status self.timer_status = TIMER_STATUS_EXPIRED @@ -211,7 +211,7 @@ def execute_operation(self, operation): self.loop_forward() def scrub_time(self, time): # used externally to set time by slider scrubbing - debug("scrub_time: {0}".format(time)) + sv_logger.debug("scrub_time: {0}".format(time)) if time == 0: self.loop_backward() @@ -229,7 +229,7 @@ def scrub_time(self, time): # used externally to set time by slider scrubbing def update_time(self, loops, speed, duration, operation, absolute, sticky): ''' Update timer's time (called from the node's update loop) ''' - # debug("Timer {0}: UPDATE with loops = {1}, speed = {2}, duration = {3}, operation = {4}".format(self.timer_id, loops, speed, duration, operation)) + # sv_logger.debug("Timer {0}: UPDATE with loops = {1}, speed = {2}, duration = {3}, operation = {4}".format(self.timer_id, loops, speed, duration, operation)) self.timer_loops = loops self.timer_speed = speed @@ -251,25 +251,25 @@ def update_time(self, loops, speed, duration, operation, absolute, sticky): else: # update based on RELATIVE frame difference delta_time = (new_frame - old_frame) / fps * self.timer_speed - # debug("timer time = {0}".format(self.timer_time)) - # debug("timer delta = {0}".format(delta_time)) + # sv_logger.debug("timer time = {0}".format(self.timer_time)) + # sv_logger.debug("timer delta = {0}".format(delta_time)) self.timer_time += delta_time # time is out of range at either ends ? => check for looping if self.timer_time < 0: if self.timer_loops: # looping ? if self.timer_loop_count == 0: # at the first loop => stop - # debug("start < looping = 0") + # sv_logger.debug("start < looping = 0") self.timer_time = 0 self.timer_status = TIMER_STATUS_STOPPED self.last_timer_status = TIMER_STATUS_STARTED else: # not at the first loop => wrap around to previous loop - # debug("start < looping > 0") + # sv_logger.debug("start < looping > 0") self.timer_time = self.timer_time % self.timer_duration self.timer_loop_count -= 1 else: # not looping => stop ? - # debug("start < NO looping") + # sv_logger.debug("start < NO looping") self.timer_time = 0 self.timer_status = TIMER_STATUS_STOPPED self.last_timer_status = TIMER_STATUS_STARTED @@ -277,18 +277,18 @@ def update_time(self, loops, speed, duration, operation, absolute, sticky): elif self.timer_time > self.timer_duration: if self.timer_loops: # looping ? if self.timer_loop_count == self.timer_loops: # at the last loop => expire - # debug("start >= looping = N") + # sv_logger.debug("start >= looping = N") self.timer_time = self.timer_duration self.timer_status = TIMER_STATUS_EXPIRED self.last_timer_status = TIMER_STATUS_STARTED else: # not at the last loop => wrap around to next loop - # debug("start >= looping < N") + # sv_logger.debug("start >= looping < N") self.timer_time = self.timer_time % self.timer_duration self.timer_loop_count += 1 else: # not looping => expire ? - # debug("start >= NO looping") + # sv_logger.debug("start >= NO looping") self.timer_time = self.timer_duration self.timer_status = TIMER_STATUS_EXPIRED self.last_timer_status = TIMER_STATUS_STARTED @@ -306,7 +306,7 @@ def update_time(self, loops, speed, duration, operation, absolute, sticky): # keep the time within range self.timer_time = max(0, min(self.timer_time, self.timer_duration)) - # debug("Timer {0}: Status = {1}, Elapsed Time = {2}, Remaining Time = {3}, Expired = {4}".format(self.id(), self.status(), self.elapsed_time(), self.remaining_time(), self.expired())) + # sv_logger.debug("Timer {0}: Status = {1}, Elapsed Time = {2}, Remaining Time = {3}, Expired = {4}".format(self.id(), self.status(), self.elapsed_time(), self.remaining_time(), self.expired())) class SvTimerOperatorCallback(bpy.types.Operator): @@ -438,47 +438,47 @@ def sv_draw_buttons_ext(self, context, layout): layout.prop(self, "sticky") def start_timer(self, context): - debug("* Timer: start_timer") + self.debug("* Timer: start_timer") for timer in self.timers: timer.start() updateNode(self, context) def stop_timer(self, context): - debug("* Timer: stop_timer") + self.debug("* Timer: stop_timer") for timer in self.timers: timer.stop() self.sync_time_slider(0) updateNode(self, context) def pause_timer(self, context): - debug("* Timer: pause_timer") + self.debug("* Timer: pause_timer") for timer in self.timers: timer.pause() updateNode(self, context) def reset_timer(self, context): - debug("* Timer: reset_timer") + self.debug("* Timer: reset_timer") for timer in self.timers: timer.reset() self.sync_time_slider(0) updateNode(self, context) def expire_timer(self, context): - debug("* Timer: expire_timer") + self.debug("* Timer: expire_timer") for timer in self.timers: timer.expire() self.sync_time_slider(1) updateNode(self, context) def loop_backward_timer(self, context): - debug("* Timer: loop_backward_timer") + self.debug("* Timer: loop_backward_timer") for timer in self.timers: timer.loop_backward() self.sync_time_slider(0) updateNode(self, context) def loop_forward_timer(self, context): - debug("* Timer: loop_forward_timer") + self.debug("* Timer: loop_forward_timer") for timer in self.timers: timer.loop_forward() self.sync_time_slider(1) @@ -517,21 +517,21 @@ def process(self): old_timer_count = len(self.timers) new_timer_count = len(parameters[0]) - # debug("we need {0} timers".format(new_timer_count)) - # debug("old_timer_count = {0}".format(old_timer_count)) - # debug("new_timer_count = {0}".format(new_timer_count)) + # self.debug("we need {0} timers".format(new_timer_count)) + # self.debug("old_timer_count = {0}".format(old_timer_count)) + # self.debug("new_timer_count = {0}".format(new_timer_count)) # did the number of timers change ? => add or remove timers if old_timer_count != new_timer_count: if new_timer_count > old_timer_count: # add new timers for n in range(old_timer_count, new_timer_count): - # debug("creating new timer: {0}".format(n)) + # self.debug("creating new timer: {0}".format(n)) timer = self.timers.add() timer.timer_id = n else: # remove old timers while len(self.timers) > new_timer_count: n = len(self.timers) - 1 - # debug("removing old timer: {0}".format(self.timers[n].timer_id)) + # self.debug("removing old timer: {0}".format(self.timers[n].timer_id)) self.timers.remove(n) # process timers diff --git a/nodes/script/formula_interpolate.py b/nodes/script/formula_interpolate.py index d7bfd1ff2a..c1f3452e95 100644 --- a/nodes/script/formula_interpolate.py +++ b/nodes/script/formula_interpolate.py @@ -23,7 +23,7 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, match_long_repeat -from sverchok.utils.logging import debug +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.modules.eval_formula import get_variables, safe_eval from sverchok.utils.geom import CubicSpline, LinearSpline from sverchok.utils.curve import SvSplineCurve @@ -61,7 +61,7 @@ def update_point(self, context): if hasattr(context, 'node') and hasattr(context.node, 'on_update'): context.node.on_update(context) else: - debug("Node is not defined in this context, so will not update the node.") + sv_logger.debug("Node is not defined in this context, so will not update the node.") x : StringProperty(name = "X", update=update_point) y : StringProperty(name = "Y", update=update_point) diff --git a/nodes/script/mesh_eval.py b/nodes/script/mesh_eval.py index 36691efc4f..2f73f0705f 100644 --- a/nodes/script/mesh_eval.py +++ b/nodes/script/mesh_eval.py @@ -19,9 +19,9 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.utils.sv_node_utils import sync_pointer_and_stored_name -from sverchok.data_structure import updateNode, dataCorrect, match_long_repeat +from sverchok.data_structure import updateNode, match_long_repeat from sverchok.utils.script_importhelper import safe_names -from sverchok.utils.logging import exception, info +from sverchok.utils.sv_logging import sv_logger """ JSON format: @@ -76,7 +76,7 @@ def eval_list(coords): val = safe_eval(c, variables) #self.debug("EVAL: {} with {} => {}".format(c, variables, val)) except NameError as e: - exception(e) + sv_logger.exception(e) val = 0.0 else: val = c diff --git a/nodes/script/profile_mk3.py b/nodes/script/profile_mk3.py index 08328787b3..fce6894009 100644 --- a/nodes/script/profile_mk3.py +++ b/nodes/script/profile_mk3.py @@ -27,7 +27,7 @@ from sverchok.utils.sv_node_utils import sync_pointer_and_stored_name from sverchok.core.sv_custom_exceptions import SvNoDataError from sverchok.data_structure import updateNode, match_long_repeat -from sverchok.utils.logging import info, debug, warning +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.curve.algorithms import concatenate_curves, unify_curves_degree from sverchok.utils.sv_update_utils import sv_get_local_path @@ -162,11 +162,11 @@ def execute(self, context): precision = node.precision subdivisions = node.curve_points_count if not bpy.context.selected_objects: - warning('Pofiler: Select curve!') + sv_logger.warning('Pofiler: Select curve!') self.report({'INFO'}, 'Select CURVE first') return {'CANCELLED'} if not bpy.context.selected_objects[0].type == 'CURVE': - warning('Pofiler: NOT a curve selected') + sv_logger.warning('Pofiler: NOT a curve selected') self.report({'INFO'}, 'It is not a curve selected for profiler') return {'CANCELLED'} @@ -177,7 +177,7 @@ def execute(self, context): spline_type = objs[0].data.splines[0].type if spline_type in {'POLY', 'NURBS'}: msg = 'Pofiler: does not support {0} curve type yet'.format(spline_type) - warning(msg) + sv_logger.warning(msg) self.report({'INFO'}, msg) return {'CANCELLED'} diff --git a/nodes/solid/export_solid.py b/nodes/solid/export_solid.py index 5bb499a8ed..e67e331ea2 100644 --- a/nodes/solid/export_solid.py +++ b/nodes/solid/export_solid.py @@ -11,7 +11,7 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import flatten_data from sverchok.utils.sv_operator_mixins import SvGenericNodeLocator -from sverchok.utils.logging import debug +from sverchok.utils.sv_logging import sv_logger from sverchok.dependencies import FreeCAD if FreeCAD is not None: @@ -47,11 +47,11 @@ def execute(self, context): base_name = "sv_solid" for i, shape in enumerate(objects): #shape = map_recursive(to_solid, object, data_types=(PartModule.Shape, SvCurve, SvSurface)) - debug("Exporting", shape) + sv_logger.debug("Exporting", shape) if isinstance(shape, (list, tuple)): shape = flatten_data(shape, data_types=(PartModule.Shape,)) if isinstance(shape, (list,tuple)): - debug("Make compound:", shape) + sv_logger.debug("Make compound:", shape) shape = PartModule.Compound(shape) file_path = folder_path + base_name + "_" + "%05d" % i diff --git a/nodes/surface/adaptive_tessellate.py b/nodes/surface/adaptive_tessellate.py index 0c94f966a1..34d25af797 100644 --- a/nodes/surface/adaptive_tessellate.py +++ b/nodes/surface/adaptive_tessellate.py @@ -1,19 +1,16 @@ -import numpy as np import bpy from bpy.props import EnumProperty, IntProperty, BoolProperty, FloatProperty -import sverchok from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level, get_data_nesting_level -from sverchok.utils.logging import info, exception -from sverchok.utils.geom_2d.merge_mesh import crop_mesh_delaunay +from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level from sverchok.utils.curve import SvCurve from sverchok.utils.surface import SvSurface from sverchok.utils.adaptive_surface import adaptive_subdivide, MAXIMUM, GAUSS, MEAN + class SvAdaptiveTessellateNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Adaptive Tessellate Surface diff --git a/nodes/surface/flip_surface.py b/nodes/surface/flip_surface.py index 7d6627a5a4..8791efc4f6 100644 --- a/nodes/surface/flip_surface.py +++ b/nodes/surface/flip_surface.py @@ -1,13 +1,12 @@ -import numpy as np import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode, ensure_nesting_level from sverchok.utils.surface import SvSurface, SvFlipSurface + class SvFlipSurfaceNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Flip Surface diff --git a/nodes/surface/nurbs_loft.py b/nodes/surface/nurbs_loft.py index 8811159cb4..d2631c61a0 100644 --- a/nodes/surface/nurbs_loft.py +++ b/nodes/surface/nurbs_loft.py @@ -4,13 +4,13 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception from sverchok.utils.math import supported_metrics from sverchok.utils.curve.core import SvCurve from sverchok.utils.curve.nurbs import SvNurbsCurve from sverchok.utils.surface.nurbs import simple_loft from sverchok.dependencies import geomdl + class SvNurbsLoftNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: NURBS Loft / Skin diff --git a/nodes/surface/revolution_surface.py b/nodes/surface/revolution_surface.py index ea849c63d9..1b8992f1b6 100644 --- a/nodes/surface/revolution_surface.py +++ b/nodes/surface/revolution_surface.py @@ -7,10 +7,10 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception from sverchok.utils.curve import SvCurve from sverchok.utils.surface.algorithms import SvRevolutionSurface + class SvRevolutionSurfaceNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Revolution Surface diff --git a/nodes/surface/ruled_surface.py b/nodes/surface/ruled_surface.py index f9b1308ddf..7bb0c5a7e9 100644 --- a/nodes/surface/ruled_surface.py +++ b/nodes/surface/ruled_surface.py @@ -1,15 +1,13 @@ -import numpy as np - import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception from sverchok.utils.curve import SvCurve from sverchok.utils.surface.algorithms import SvCurveLerpSurface + class SvCurveLerpNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Curve Lerp Linear Ruled Surface diff --git a/nodes/surface/subdomain.py b/nodes/surface/subdomain.py index 4fa4aa6b85..b962830c98 100644 --- a/nodes/surface/subdomain.py +++ b/nodes/surface/subdomain.py @@ -1,14 +1,12 @@ -import numpy as np - import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception from sverchok.utils.surface import SvSurface, SvSurfaceSubdomain + class SvSurfaceSubdomainNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Surface Subdomain (iso trim) diff --git a/nodes/surface/surface_bevel_curve.py b/nodes/surface/surface_bevel_curve.py index ccf26ccccf..a1593d814f 100644 --- a/nodes/surface/surface_bevel_curve.py +++ b/nodes/surface/surface_bevel_curve.py @@ -12,7 +12,6 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level, get_data_nesting_level -from sverchok.utils.logging import info, exception from sverchok.utils.curve import SvCurve from sverchok.utils.curve.algorithms import SvIsoUvCurve from sverchok.utils.curve.nurbs import SvNurbsCurve diff --git a/nodes/surface/surface_lerp.py b/nodes/surface/surface_lerp.py index 4ccde2c598..b7a2ee1a95 100644 --- a/nodes/surface/surface_lerp.py +++ b/nodes/surface/surface_lerp.py @@ -1,15 +1,13 @@ -import numpy as np - import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception from sverchok.utils.surface.core import SvSurface from sverchok.utils.surface.algorithms import SvSurfaceLerpSurface + class SvSurfaceLerpNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Surface Lerp Linear diff --git a/nodes/surface/surface_reduce_degree.py b/nodes/surface/surface_reduce_degree.py index f51aef8140..b09f004cf2 100644 --- a/nodes/surface/surface_reduce_degree.py +++ b/nodes/surface/surface_reduce_degree.py @@ -110,7 +110,7 @@ def process(self): kwargs = dict(target = degree) surface = surface.reduce_degree(self.direction, tolerance = tolerance, - logger = self.get_logger(), + logger = self.sv_logger, **kwargs) new_surfaces.append(surface) if flat_output: diff --git a/nodes/surface/surface_reparametrize.py b/nodes/surface/surface_reparametrize.py index 7750f842c0..3d017dc7ba 100644 --- a/nodes/surface/surface_reparametrize.py +++ b/nodes/surface/surface_reparametrize.py @@ -1,13 +1,12 @@ -import numpy as np import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception from sverchok.utils.surface import SvSurface, SvReparametrizedSurface + class SvReparametrizeSurfaceNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Reparametrize Surface diff --git a/nodes/surface/swap.py b/nodes/surface/swap.py index 18bb174be7..3223414211 100644 --- a/nodes/surface/swap.py +++ b/nodes/surface/swap.py @@ -1,13 +1,11 @@ -import numpy as np import bpy -from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level -from sverchok.utils.logging import info, exception +from sverchok.data_structure import ensure_nesting_level from sverchok.utils.surface import SvSurface, SvSwapSurface + class SvSwapSurfaceNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Swap Surface diff --git a/nodes/surface/taper_sweep.py b/nodes/surface/taper_sweep.py index b204153751..5f148101e7 100644 --- a/nodes/surface/taper_sweep.py +++ b/nodes/surface/taper_sweep.py @@ -6,12 +6,12 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level, get_data_nesting_level -from sverchok.utils.logging import info, exception from sverchok.utils.curve import SvCurve from sverchok.utils.curve.nurbs import SvNurbsCurve from sverchok.utils.surface.algorithms import SvTaperSweepSurface from sverchok.utils.surface.bevel_curve import nurbs_taper_sweep + class SvTaperSweepSurfaceNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Taper Sweep Curve diff --git a/nodes/surface/tessellate_trim.py b/nodes/surface/tessellate_trim.py index baf5382a4c..9d1cd45d34 100644 --- a/nodes/surface/tessellate_trim.py +++ b/nodes/surface/tessellate_trim.py @@ -4,10 +4,8 @@ import bpy from bpy.props import EnumProperty, IntProperty -import sverchok from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level, get_data_nesting_level -from sverchok.utils.logging import info, exception +from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level from sverchok.utils.geom_2d.merge_mesh import crop_mesh_delaunay from sverchok.utils.sv_mesh_utils import mesh_join @@ -18,6 +16,7 @@ # since Blender 2.81 only. So the node will not be available in # Blender 2.80. + class SvExTessellateTrimSurfaceNode(SverchCustomTreeNode, bpy.types.Node): """ Triggers: Tessellate Trim Surface diff --git a/nodes/viz/mesh_viewer.py b/nodes/viz/mesh_viewer.py index f0a1a14095..0836b6a492 100644 --- a/nodes/viz/mesh_viewer.py +++ b/nodes/viz/mesh_viewer.py @@ -17,7 +17,7 @@ from sverchok.utils.handle_blender_data import correct_collection_length from sverchok.utils.nodes_mixins.show_3d_properties import Show3DProperties import sverchok.utils.meshes as me -from sverchok.utils.logging import fix_error_msg +from sverchok.utils.sv_logging import fix_error_msg class SvMeshViewer(Show3DProperties, SvViewerNode, SverchCustomTreeNode, bpy.types.Node): diff --git a/old_nodes/__init__.py b/old_nodes/__init__.py index 273f6f7690..aeb0ce3eb3 100644 --- a/old_nodes/__init__.py +++ b/old_nodes/__init__.py @@ -25,7 +25,7 @@ import bpy from sverchok.utils.sv_oldnodes_parser import get_old_node_bl_idnames -from sverchok.utils.logging import error +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.handle_blender_data import BlTrees @@ -128,7 +128,7 @@ def register_all(): # when a code of an old node is copied to old folder # it can be copied with other classes (property groups) # which does not change it version to MK2, so we have the error - error(e) + sv_logger.error(e) def register(): @@ -145,4 +145,4 @@ def unregister(): try: mod.unregister() except Exception as e: - error(e) + sv_logger.error(e) diff --git a/old_nodes/formula3.py b/old_nodes/formula3.py index 5b3a804817..91580f4207 100644 --- a/old_nodes/formula3.py +++ b/old_nodes/formula3.py @@ -24,7 +24,7 @@ from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, match_long_repeat, zip_long_repeat -from sverchok.utils import logging +from sverchok.utils import sv_logging from sverchok.utils.modules.eval_formula import get_variables, safe_eval class SvFormulaNodeMk3(SverchCustomTreeNode, bpy.types.Node): diff --git a/old_nodes/levels.py b/old_nodes/levels.py index 6aed2926b6..4a4c85451f 100644 --- a/old_nodes/levels.py +++ b/old_nodes/levels.py @@ -25,18 +25,20 @@ from sverchok.utils.curve.core import SvCurve from sverchok.utils.surface.core import SvSurface from sverchok.dependencies import FreeCAD -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger + ALL_TYPES = SIMPLE_DATA_TYPES + (SvCurve, SvSurface) if FreeCAD is not None: import Part ALL_TYPES = ALL_TYPES + (Part.Shape,) + class SvNestingLevelEntry(bpy.types.PropertyGroup): def update_entry(self, context): if hasattr(context, 'node'): updateNode(context.node, context) else: - info("Node is not defined in this context, so will not update the node.") + sv_logger.info("Node is not defined in this context, so will not update the node.") description : StringProperty(options = {'SKIP_SAVE'}, default="?") flatten : BoolProperty( diff --git a/old_nodes/mesh_select.py b/old_nodes/mesh_select.py index fca94a31e7..61eb260562 100644 --- a/old_nodes/mesh_select.py +++ b/old_nodes/mesh_select.py @@ -24,11 +24,10 @@ from bpy.props import IntProperty, FloatProperty, BoolProperty, EnumProperty from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, match_long_repeat, describe_data_shape -from sverchok.utils.logging import info, debug -from sverchok.utils.sv_bmesh_utils import bmesh_from_pydata, pydata_from_bmesh +from sverchok.data_structure import updateNode, match_long_repeat from sverchok.utils.sv_mesh_utils import calc_mesh_normals_bmesh as calc_mesh_normals + class SvMeshSelectNode(SverchCustomTreeNode, bpy.types.Node): '''Select vertices, edges, faces by geometric criteria''' bl_idname = 'SvMeshSelectNode' @@ -309,7 +308,7 @@ def _process(self, meshes): out_faces = [] for vertices, edges, faces in zip(*meshes): - #debug("Level 2, shape: %s", describe_data_shape(vertices)) + # self.debug("Level 2, shape: %s", describe_data_shape(vertices)) if self.mode == 'BySide': vs, es, fs = self.by_side(vertices, edges, faces) elif self.mode == 'ByNormal': @@ -344,12 +343,12 @@ def _process_recursive(self, level, meshes): out_faces = [] for vertices_s, edges_s, faces_s in zip(*meshes): - #debug("Level: %s, shape: %s", level, describe_data_shape(vertices_s)) + # self.debug("Level: %s, shape: %s", level, describe_data_shape(vertices_s)) if not edges_s: edges_s = [[]] if not faces_s: faces_s = [[]] - debug("Level: %s, edges: %s", level, edges_s) + self.debug("Level: %s, edges: %s", level, edges_s) sub_meshes = match_long_repeat([vertices_s, edges_s, faces_s]) vs, es, fs = self._process_recursive(level-1, sub_meshes) out_vertices.append(vs) diff --git a/old_nodes/remove_doubles.py b/old_nodes/remove_doubles.py index cd72f8f6c8..5d71f2bae3 100644 --- a/old_nodes/remove_doubles.py +++ b/old_nodes/remove_doubles.py @@ -21,8 +21,8 @@ import bmesh from sverchok.node_tree import SverchCustomTreeNode -from sverchok.data_structure import updateNode, Vector_generate, repeat_last, zip_long_repeat -from sverchok.utils.logging import info, debug +from sverchok.data_structure import updateNode, Vector_generate, zip_long_repeat +from sverchok.utils.sv_logging import sv_logger # # Remove Doubles @@ -75,7 +75,7 @@ def remove_doubles(vertices, faces, d, face_data=None, find_doubles=False): if 0 <= initial_face_index < len(face_data): face_data_o = face_data[initial_face_index] else: - info("No face data for face #%s", initial_face_index) + sv_logger.info("No face data for face #%s", initial_face_index) face_data_o = None face_data_out.append(face_data_o) diff --git a/settings.py b/settings.py index 3f39441b86..3b33a72995 100644 --- a/settings.py +++ b/settings.py @@ -1,6 +1,7 @@ +import logging import sys import os -from os.path import dirname, basename, join +from os.path import basename, join import subprocess from glob import glob import shutil @@ -28,7 +29,6 @@ # names from other modules sv_dependencies, pip, ensurepip, draw_message, get_icon = [None] * 5 set_frame_change = None -info, setLevel = [None] * 2 draw_extra_addons = None apply_theme, rebuild_color_cache, color_callback = [None] * 3 @@ -378,8 +378,9 @@ def set_nodeview_render_params(self, context): # Logging settings def update_log_level(self, context): - info("Setting log level to %s", self.log_level) - setLevel(self.log_level) + sv_logger = logging.getLogger('sverchok') + sv_logger.info("Setting log level to %s", self.log_level) + sv_logger.setLevel(self.log_level) log_levels = [ ("DEBUG", "Debug", "Debug output", 0), diff --git a/tests/bezier_tests.py b/tests/bezier_tests.py index 087bbfaeca..93b6daa787 100644 --- a/tests/bezier_tests.py +++ b/tests/bezier_tests.py @@ -1,10 +1,10 @@ import numpy as np -from sverchok.utils.logging import error from sverchok.utils.testing import * from sverchok.utils.curve import SvCubicBezierCurve, SvBezierCurve + def cubic_control_points(): return [ [0.0, 0.0, 0.0], diff --git a/tests/core_tests.py b/tests/core_tests.py index d9e63ee832..591d37d617 100644 --- a/tests/core_tests.py +++ b/tests/core_tests.py @@ -1,9 +1,8 @@ -from pathlib import Path import importlib from sverchok.utils.testing import * -from sverchok.utils.logging import debug, info, exception + class CoreTests(SverchokTestCase): @@ -25,7 +24,7 @@ def test_imports(self): try: module = importlib.import_module(module_name) except Exception as e: - exception(e) + sv_logger.exception(e) self.fail(str(e)) self.assertIsNotNone(module) diff --git a/tests/cubic_spline_tests.py b/tests/cubic_spline_tests.py index 2003b16b11..ef1da4a12d 100644 --- a/tests/cubic_spline_tests.py +++ b/tests/cubic_spline_tests.py @@ -1,10 +1,9 @@ import numpy as np from sverchok.utils.testing import * -from sverchok.utils.logging import debug, info from sverchok.utils.geom import CubicSpline from sverchok.utils.curve.bezier import SvBezierCurve -from sverchok.utils.curve.algorithms import concatenate_curves, reparametrize_curve + class CubicSplineTests(SverchokTestCase): def setUp(self): diff --git a/tests/curve_tests.py b/tests/curve_tests.py index 1aea7e8aa1..1a0bad6b35 100644 --- a/tests/curve_tests.py +++ b/tests/curve_tests.py @@ -1,9 +1,7 @@ -import numpy as np -import unittest - -from sverchok.utils.testing import SverchokTestCase, requires +from sverchok.utils.testing import SverchokTestCase from sverchok.utils.curve.core import * + class TaylorTests(SverchokTestCase): def test_square_1(self): coeffs = np.array([[4,0,0], [3,0,0], [2,0,0], [1,0,0]], dtype=np.float64) diff --git a/tests/data_structure_tests.py b/tests/data_structure_tests.py index 5911abb865..3a7e04793d 100644 --- a/tests/data_structure_tests.py +++ b/tests/data_structure_tests.py @@ -1,10 +1,7 @@ - -import unittest - -from sverchok.utils.logging import error from sverchok.utils.testing import * from sverchok.data_structure import * + class DataStructureTests(SverchokTestCase): def test_match_long_repeat(self): inputs = [[1,2,3,4,5], [10,11]] @@ -80,7 +77,7 @@ def test_ensure_nesting_level_2(self): with self.assertRaises(TypeError): data = [[[17]]] result = ensure_nesting_level(data, 1) - error("ensure_nesting_level() returned %s", result) + sv_logger.error("ensure_nesting_level() returned %s", result) def test_transpose_list(self): self.subtest_assert_equals(transpose_list([[1,2], [3,4]]), [[1,3], [2, 4]]) diff --git a/tests/diameter_tests.py b/tests/diameter_tests.py index bafbb29f70..6b8dabf18e 100644 --- a/tests/diameter_tests.py +++ b/tests/diameter_tests.py @@ -1,11 +1,10 @@ from math import sqrt -from mathutils import Vector -from sverchok.utils.logging import error from sverchok.utils.testing import * from sverchok.utils.geom import diameter + class DiameterTests(SverchokTestCase): def test_diameter_1(self): p1 = (0, 0, 0) diff --git a/tests/dict_tests.py b/tests/dict_tests.py index bda56dfab2..2f7b968697 100644 --- a/tests/dict_tests.py +++ b/tests/dict_tests.py @@ -1,11 +1,9 @@ -import unittest - -from sverchok.utils.logging import error from sverchok.utils.testing import * from sverchok.utils.dictionary import SvApproxDict from sverchok.utils.curve.nurbs_algorithms import KnotvectorDict + class ApproxDictTests(SverchokTestCase): def test_repr(self): diff --git a/tests/docs_tests.py b/tests/docs_tests.py index d1966a8df1..36318022e6 100644 --- a/tests/docs_tests.py +++ b/tests/docs_tests.py @@ -1,4 +1,3 @@ -import sverchok from sverchok.utils.testing import * diff --git a/tests/formula_interpolate_tests.py b/tests/formula_interpolate_tests.py index 9f3b2027d8..c740868f9c 100644 --- a/tests/formula_interpolate_tests.py +++ b/tests/formula_interpolate_tests.py @@ -1,14 +1,8 @@ -import unittest -from os.path import basename, splitext, dirname, join, exists -from os import walk -from glob import glob - -import sverchok from sverchok.utils.testing import * -from sverchok.utils.logging import debug, info, error from sverchok.nodes.script.formula_interpolate import ControlPoint, split_points + class DocumentationTests(SverchokTestCase): def test_empty(self): points = [] diff --git a/tests/general_fuse_tests.py b/tests/general_fuse_tests.py index 30321c3fb9..15f94bd4c8 100644 --- a/tests/general_fuse_tests.py +++ b/tests/general_fuse_tests.py @@ -1,7 +1,5 @@ -from sverchok.data_structure import get_data_nesting_level from sverchok.utils.testing import * -from sverchok.utils.logging import debug, info from sverchok.dependencies import FreeCAD if FreeCAD is not None: diff --git a/tests/geom_tests.py b/tests/geom_tests.py index c085f1f2b0..91f0476fdb 100644 --- a/tests/geom_tests.py +++ b/tests/geom_tests.py @@ -1,15 +1,11 @@ -import unittest -import numpy as np -import math - from mathutils import Vector, Matrix -from sverchok.utils.logging import error from sverchok.utils.testing import * from sverchok.utils.geom import * from sverchok.utils.curve.primitives import SvCircle + class GeometryTests(SverchokTestCase): def test_center_trivial(self): diff --git a/tests/init_tests.py b/tests/init_tests.py index 64205a3920..2a1ab7cabb 100644 --- a/tests/init_tests.py +++ b/tests/init_tests.py @@ -1,11 +1,8 @@ -import bpy import addon_utils -import unittest - from sverchok.utils.testing import * -from sverchok.utils.logging import debug, info + @unittest.skip("Disabled temporarily") class InitTests(SverchokTestCase): @@ -17,8 +14,8 @@ def test_core_exists(self): def test_disable_enable(self): with self.assert_logs_no_errors(): - info("Disabling Sverchok") + sv_logger.info("Disabling Sverchok") addon_utils.disable("sverchok") - info("Enabling Sverchok") + sv_logger.info("Enabling Sverchok") addon_utils.enable("sverchok") diff --git a/tests/issue_4469_tests.py b/tests/issue_4469_tests.py index bf5a73164d..c1ede3fda4 100644 --- a/tests/issue_4469_tests.py +++ b/tests/issue_4469_tests.py @@ -2,8 +2,6 @@ import unittest from sverchok.utils.testing import SverchokTestCase, requires -from sverchok.utils.curve import knotvector as sv_knotvector -from sverchok.utils.curve.nurbs import SvGeomdlCurve, SvNativeNurbsCurve, SvNurbsBasisFunctions, SvNurbsCurve from sverchok.utils.nurbs_common import SvNurbsBasisFunctions from sverchok.dependencies import geomdl diff --git a/tests/issue_4757_tests.py b/tests/issue_4757_tests.py index 3c2247f0d8..fd501ddc40 100644 --- a/tests/issue_4757_tests.py +++ b/tests/issue_4757_tests.py @@ -1,21 +1,14 @@ import numpy as np -import unittest -from math import pi -from mathutils import Matrix - -from sverchok.utils.testing import SverchokTestCase, requires -from sverchok.utils.geom import circle_by_three_points +from sverchok.utils.testing import SverchokTestCase from sverchok.utils.curve import knotvector as sv_knotvector -from sverchok.utils.curve.primitives import SvCircle from sverchok.utils.curve.algorithms import concatenate_curves -from sverchok.utils.curve.nurbs import SvGeomdlCurve, SvNativeNurbsCurve, SvNurbsBasisFunctions, SvNurbsCurve +from sverchok.utils.curve.nurbs import SvNurbsCurve from sverchok.utils.curve.nurbs_algorithms import concatenate_nurbs_curves -from sverchok.utils.nurbs_common import SvNurbsMaths, elevate_bezier_degree, from_homogenous -from sverchok.utils.surface.nurbs import SvGeomdlSurface, SvNativeNurbsSurface -from sverchok.utils.surface.algorithms import SvCurveLerpSurface +from sverchok.utils.nurbs_common import SvNurbsMaths from sverchok.dependencies import geomdl, FreeCAD + class ConcatenateTests(SverchokTestCase): def test_concat_4757(self): diff --git a/tests/json_import_simple_tests.py b/tests/json_import_simple_tests.py index 2655319eca..14bc2dbe9f 100644 --- a/tests/json_import_simple_tests.py +++ b/tests/json_import_simple_tests.py @@ -1,8 +1,7 @@ -import json - from sverchok.utils.testing import * + class ImportSingleSimpleNode(EmptyTreeTestCase): def test_box_import(self): diff --git a/tests/json_import_tests.py b/tests/json_import_tests.py index 9eae4bfa10..d5de1db9fb 100644 --- a/tests/json_import_tests.py +++ b/tests/json_import_tests.py @@ -74,7 +74,7 @@ def test_import_examples(self): for examples_path, category_name in example_categories_names(): - info("Opening Dir named: %s", category_name) + sv_logger.debug("Opening Dir named: %s", category_name) examples_set = examples_path / category_name for listed_path in examples_set.iterdir(): @@ -86,7 +86,7 @@ def test_import_examples(self): name = basename(path) if name in UNITTEST_SKIPLIST: - info(f"Skipping test import of: {name} - to permit unit-tests to continue") + sv_logger.info(f"Skipping test import of: {name} - the tree in the skip list") continue with self.subTest(file=name): diff --git a/tests/linear_approximation_tests.py b/tests/linear_approximation_tests.py index d195b7ab21..d6d75ef7c4 100644 --- a/tests/linear_approximation_tests.py +++ b/tests/linear_approximation_tests.py @@ -1,7 +1,6 @@ import numpy as np from sverchok.utils.testing import * -from sverchok.utils.logging import debug, info from sverchok.utils.geom import PlaneEquation, LineEquation, linear_approximation class PlaneTests(SverchokTestCase): diff --git a/tests/linear_spline_tests.py b/tests/linear_spline_tests.py index 5517317cbb..abe6b07b9c 100644 --- a/tests/linear_spline_tests.py +++ b/tests/linear_spline_tests.py @@ -1,9 +1,9 @@ import numpy as np from sverchok.utils.testing import * -from sverchok.utils.logging import debug, info from sverchok.utils.geom import LinearSpline + class LinearSplineTests(SverchokTestCase): def setUp(self): super().setUp() diff --git a/tests/math_tests.py b/tests/math_tests.py index bb2ffba96c..ce56009126 100644 --- a/tests/math_tests.py +++ b/tests/math_tests.py @@ -1,9 +1,7 @@ - -import unittest - from sverchok.utils.testing import * from sverchok.utils.math import * + class MathTests(SverchokTestCase): def test_distribute_int_1(self): n = 10 diff --git a/tests/nurbs_tests.py b/tests/nurbs_tests.py index abba501e2f..eee95f7cee 100644 --- a/tests/nurbs_tests.py +++ b/tests/nurbs_tests.py @@ -526,7 +526,7 @@ def test_remove_2(self): inserted_kv = inserted.get_knotvector() k = np.searchsorted(inserted_kv, knot, side='right')-1 s = sv_knotvector.find_multiplicity(inserted_kv, knot) - print("K:", k, "S:", s) + # print("K:", k, "S:", s) removed = inserted.remove_knot(knot, 1) self.assert_numpy_arrays_equal(removed.get_knotvector(), kv, precision=8) diff --git a/tests/profile_mk3_tests.py b/tests/profile_mk3_tests.py index 9c684695da..da387db6d3 100644 --- a/tests/profile_mk3_tests.py +++ b/tests/profile_mk3_tests.py @@ -1,14 +1,9 @@ -from pathlib import Path -from os.path import basename - -from sverchok.utils.logging import error from sverchok.utils.testing import * -from sverchok.utils.parsec import parse -from sverchok.utils.modules.profile_mk3.interpreter import * from sverchok.utils.modules.profile_mk3.parser import * from sverchok.nodes.script.profile_mk3 import profile_template_path + class SimpleTests(SverchokTestCase): def test_identifier(self): result = parse(parse_identifier, "z") @@ -114,7 +109,7 @@ def test_import_examples(self): with self.subTest(file=name): with open(path, 'r') as f: - info("Checking profile example: %s", name) + sv_logger.info("Checking profile example: %s", name) profile_text = f.read() with self.assert_logs_no_errors(): parse_profile(profile_text) diff --git a/tests/simple_generator_tests.py b/tests/simple_generator_tests.py index 12c5ef8174..67fc4cc10c 100644 --- a/tests/simple_generator_tests.py +++ b/tests/simple_generator_tests.py @@ -1,6 +1,5 @@ from sverchok.utils.testing import * -from sverchok.utils.logging import debug, info # Some "smoke tests" for simple generator nodes. # These test cases exist mostly in demonstration purposes, @@ -8,6 +7,7 @@ # Failure of these tests can also indicate that something # is badly broken in general node processing mechanism. + class BoxNodeTest(NodeProcessTestCase): node_bl_idname = "SvBoxNodeMk2" connect_output_sockets = ["Vers"] diff --git a/tests/simple_viewer_text_tests.py b/tests/simple_viewer_text_tests.py index 0f801e27a1..17e4b7b92b 100644 --- a/tests/simple_viewer_text_tests.py +++ b/tests/simple_viewer_text_tests.py @@ -1,7 +1,6 @@ -import bpy from sverchok.utils.testing import * -from sverchok.utils.logging import debug, info + class TextViewerTest(EmptyTreeTestCase): diff --git a/tests/socket_conversion_tests.py b/tests/socket_conversion_tests.py index 22da3d21ed..9adb31bfdb 100644 --- a/tests/socket_conversion_tests.py +++ b/tests/socket_conversion_tests.py @@ -1,8 +1,7 @@ from sverchok.core.update_system import prepare_input_data -from mathutils import Matrix from sverchok.core.sv_custom_exceptions import ImplicitConversionProhibited from sverchok.utils.testing import * -from sverchok.utils.logging import debug, info, error + class SocketConversionTests(EmptyTreeTestCase): @@ -89,11 +88,11 @@ def test_adaptive_sockets(self): 'SvFormulaNodeMk5': ["x", "y"], 'SvSetDataObjectNodeMK2': ["Objects"] } - info("starting socket conversion tests") + for bl_idname in tested_nodes.keys(): with self.subTest(bl_idname = bl_idname): - # info(f"creating SvNGonNode and {bl_idname}") + # sv_logger.info(f"creating SvNGonNode and {bl_idname}") ngon = create_node("SvNGonNode") node = create_node(bl_idname) @@ -101,7 +100,7 @@ def test_adaptive_sockets(self): node.formula = "__str__()" for input_name in tested_nodes[bl_idname]: - # info(f"Linking {ngon.name}'s vertex output ----> ({bl_idname}).inputs[{input_name}]") + # sv_logger.info(f"Linking {ngon.name}'s vertex output ----> ({bl_idname}).inputs[{input_name}]") self.tree.links.new(ngon.outputs["Vertices"], node.inputs[input_name]) # Trigger processing of the NGon node, @@ -120,7 +119,7 @@ def test_adaptive_sockets(self): except ImplicitConversionProhibited as e: raise e except Exception as e: - info(e) + sv_logger.info(e) finally: self.tree.nodes.remove(node) self.tree.nodes.remove(ngon) diff --git a/tests/ui_tests.py b/tests/ui_tests.py index 2c650fef8e..b6a05f9491 100644 --- a/tests/ui_tests.py +++ b/tests/ui_tests.py @@ -1,15 +1,13 @@ from os import walk -from os.path import basename, splitext, dirname, join, exists +from os.path import splitext from glob import glob import importlib from inspect import getmembers, isclass, getfile -import sverchok from sverchok.utils.testing import * -from sverchok.utils.logging import debug, info, error from sverchok.utils import yaml_parser -from sverchok.node_tree import SverchCustomTreeNode + sverchok_directory = dirname(getfile(sverchok)) @@ -18,7 +16,7 @@ def test_all_nodes_have_icons(self): def has_icon(node_class): has_sv_icon = hasattr(node_class, "sv_icon") has_bl_icon = hasattr(node_class, "bl_icon") and node_class.bl_icon and node_class.bl_icon != 'OUTLINER_OB_EMPTY' - #debug("Icon: %s: BL %s, SV %s", node_class.__name__, getattr(node_class, 'bl_icon', None), getattr(node_class, 'sv_icon', None)) + # sv_logger.debug("Icon: %s: BL %s, SV %s", node_class.__name__, getattr(node_class, 'bl_icon', None), getattr(node_class, 'sv_icon', None)) return has_sv_icon or has_bl_icon ignore_list = [ @@ -49,7 +47,7 @@ def check_category(directory): continue if node_class_name in ignore_list: continue - debug("Check: %s: %s: %s", node_class, node_class.__bases__, SverchCustomTreeNode in node_class.__bases__) + sv_logger.debug("Check: %s: %s: %s", node_class, node_class.__bases__, SverchCustomTreeNode in node_class.__bases__) if SverchCustomTreeNode in node_class.mro(): with self.subTest(node = node_class_name): if not has_icon(node_class): diff --git a/ui/bgl_callback_nodeview.py b/ui/bgl_callback_nodeview.py index c5c1c688ec..f7f4940808 100644 --- a/ui/bgl_callback_nodeview.py +++ b/ui/bgl_callback_nodeview.py @@ -28,7 +28,7 @@ from bpy.types import SpaceNodeEditor from sverchok.utils.sv_stethoscope_helper import draw_text_data, draw_graphical_data -from sverchok.utils.logging import debug +from sverchok.utils.sv_logging import sv_logger callback_dict = {} point_dict = {} @@ -214,7 +214,7 @@ def _draw_text_handler(tree_id, node_id, text: str, color=(1, 1, 1, 1), scale=1. # this is less efficient because it requires search of the node each redraw call if not text_coordinates: if not any(n for n in editor.edit_tree.nodes if n.node_id == node_id): - debug(f'Some node looks like was removed without removing bgl drawing, text: {text}') + sv_logger.debug(f'Some node looks like was removed without removing bgl drawing, text: {text}') return # find node location @@ -267,7 +267,7 @@ def _get_text_location(node, align='RIGHT') -> tuple[int, int]: elif align == "DOWN": x, y = int(x), int(y - dy - gap) else: - debug(f'Some node drawing text with unsupported align: {align}') + sv_logger.debug(f'Some node drawing text with unsupported align: {align}') return x, y diff --git a/ui/color_def.py b/ui/color_def.py index 92492bd08c..b7d446e6d5 100644 --- a/ui/color_def.py +++ b/ui/color_def.py @@ -21,7 +21,7 @@ from bpy.props import StringProperty import sverchok.settings as settings -from sverchok.utils.logging import debug +from sverchok.utils.sv_logging import sv_logger import sverchok from sverchok.utils.handle_blender_data import BlTrees from sverchok.ui.nodeview_space_menu import get_add_node_menu @@ -119,7 +119,7 @@ def get_color(bl_id): Get color for bl_id """ if not colors_cache: - debug("building color cache") + sv_logger.debug("building color cache") rebuild_color_cache() return colors_cache.get(bl_id) diff --git a/ui/nodes_replacement.py b/ui/nodes_replacement.py index 2226f9f5b4..6a69f4b328 100644 --- a/ui/nodes_replacement.py +++ b/ui/nodes_replacement.py @@ -19,7 +19,8 @@ import bpy -from sverchok.utils.logging import debug, info +from sverchok.utils.sv_logging import sv_logger + class SvSocketReplacement(bpy.types.PropertyGroup): """ @@ -120,7 +121,7 @@ def execute(self, context): msg = "Node `{}' ({}) has been replaced with new node `{}' ({})".format( old_node.name, old_node.bl_idname, new_node.name, new_node.bl_idname) - info(msg) + sv_logger.info(msg) self.report({'INFO'}, msg) diff --git a/ui/nodeview_space_menu.py b/ui/nodeview_space_menu.py index 0f2068b849..b7f553c69b 100644 --- a/ui/nodeview_space_menu.py +++ b/ui/nodeview_space_menu.py @@ -16,6 +16,7 @@ # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### +import logging from abc import ABC, abstractmethod from collections import defaultdict from pathlib import Path @@ -33,7 +34,6 @@ from sverchok.utils.context_managers import sv_preferences from sverchok.utils import yaml_parser from sverchok.utils.modules_inspection import iter_classes_from_module -from sverchok.utils.logging import info, debug """ @@ -67,7 +67,7 @@ - UiToolsPartialMenu """ - +logger = logging.getLogger('sverchok') CutSelf = TypeVar("CutSelf", bound="Category") sv_tree_types = {'SverchCustomTreeType', } @@ -489,9 +489,9 @@ def setup_add_menu(): use_preset_copy = False if use_preset_copy and not menu_file.exists(): - info(f"Applying menu preset {default_menu_file} at startup") + logger.info(f"Applying menu preset {default_menu_file} at startup") shutil.copy(default_menu_file, menu_file) - debug(f"Using menu preset file: {menu_file}") + logger.debug(f"Using menu preset file: {menu_file}") add_node_menu = Category.from_config(yaml_parser.load(menu_file), 'All Categories', icon_name='RNA') def get_add_node_menu(): diff --git a/ui/presets.py b/ui/presets.py index eeaa0aaeec..f12b0c436f 100644 --- a/ui/presets.py +++ b/ui/presets.py @@ -29,7 +29,7 @@ import bpy from bpy.props import StringProperty, BoolProperty, EnumProperty -from sverchok.utils.logging import debug, info, error, exception +from sverchok.utils.sv_logging import sv_logger from sverchok.utils import sv_gist_tools from sverchok.utils import sv_IO_panel_tools from sverchok.utils.sv_json_import import JSONImporter @@ -234,14 +234,14 @@ def keywords(self): def save(self): if self._data is None: - debug("Preset `%s': no data was loaded, nothing to save.", self.name) + sv_logger.debug("Preset `%s': no data was loaded, nothing to save.", self.name) return data = json.dumps(self.data, sort_keys=True, indent=2).encode('utf8') with open(self.path, 'wb') as jsonfile: jsonfile.write(data) - info("Saved preset `%s'", self.name) + sv_logger.info("Saved preset `%s'", self.name) @staticmethod def get_target_location(node_tree): @@ -251,7 +251,7 @@ def get_target_location(node_tree): """ selection = [node for node in node_tree.nodes if node.select] if not len(selection): - debug("No selection, using all nodes") + sv_logger.debug("No selection, using all nodes") selection = node_tree.nodes[:] n = len(selection) if not n: @@ -321,7 +321,7 @@ def invoke(self, context, event): preset_add_operators[(self.category, self.name)] = SverchPresetAddOperator bpy.utils.register_class(SverchPresetAddOperator) - #debug("Registered: %s", + # sv_logger.debug("Registered: %s", # "node.sv_preset_" + get_preset_idname_for_operator(self.name, self.category)) def draw_operator(self, layout, id_tree, category=None): @@ -420,13 +420,13 @@ class SvSaveSelected(bpy.types.Operator): def execute(self, context): if not self.id_tree: msg = "Node tree is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} if not self.preset_name: msg = "Preset name is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} @@ -435,7 +435,7 @@ def execute(self, context): nodes = list(filter(lambda n: n.select, ng.nodes)) if not len(nodes): msg = "There are no selected nodes to export" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} @@ -451,7 +451,7 @@ def execute(self, context): json.dump(layout_dict, open(destination_path, 'w'), indent=2) # sort keys is not expected by the exporter msg = 'exported to: ' + destination_path self.report({"INFO"}, msg) - info(msg) + sv_logger.info(msg) return {'FINISHED'} @@ -501,13 +501,13 @@ def draw(self, context): def execute(self, context): if not self.old_name: msg = "Old preset name is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} if not self.new_name: msg = "New preset name is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} @@ -525,14 +525,14 @@ def execute(self, context): if os.path.exists(new_path): msg = "Preset named `{}' already exists. Refusing to rewrite existing preset.".format(self.new_name) - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} os.rename(old_path, new_path) preset.name = self.new_name preset.category = self.new_category - info("Renamed `%s' to `%s'", old_path, new_path) + sv_logger.info("Renamed `%s' to `%s'", old_path, new_path) self.report({'INFO'}, "Renamed `{}' to `{}'".format(self.old_name, self.new_name)) bpy.utils.unregister_class(preset_add_operators[(self.old_category, self.old_name)]) @@ -566,14 +566,14 @@ class SvDeletePreset(bpy.types.Operator): def execute(self, context): if not self.preset_name: msg = "Preset name is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} path = get_preset_path(self.preset_name, category=self.category) os.remove(path) - info("Removed `%s'", path) + sv_logger.info("Removed `%s'", path) self.report({'INFO'}, "Removed `{} / {}'".format(self.category, self.preset_name)) return {'FINISHED'} @@ -597,7 +597,7 @@ class SvPresetToGist(bpy.types.Operator): def execute(self, context): if not self.preset_name: msg = "Preset name is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} @@ -611,11 +611,11 @@ def execute(self, context): try: gist_url = sv_gist_tools.main_upload_function(gist_filename, gist_description, gist_body, show_browser=False) context.window_manager.clipboard = gist_url # full destination url - info(gist_url) + sv_logger.info(gist_url) self.report({'WARNING'}, "Copied gist URL to clipboard") sv_gist_tools.write_or_append_datafiles(gist_url, gist_filename) except Exception as err: - exception(err) + sv_logger.exception(err) self.report({'ERROR'}, "Error 222: net connection or github login failed!") return {'CANCELLED'} @@ -644,20 +644,20 @@ class SvPresetToFile(bpy.types.Operator): def execute(self, context): if not self.preset_name: msg = "Preset name is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} if not self.filepath: msg = "Target file path is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} existing_path = get_preset_path(self.preset_name, category=self.category) shutil.copy(existing_path, self.filepath) msg = "Saved `{} / {}' as `{}'".format(self.category, self.preset_name, self.filepath) - info(msg) + sv_logger.info(msg) self.report({'INFO'}, msg) return {'FINISHED'} @@ -689,20 +689,20 @@ class SvPresetFromFile(bpy.types.Operator): def execute(self, context): if not self.preset_name: msg = "Preset name is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} if not self.filepath: msg = "Source file path is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} target_path = get_preset_path(self.preset_name, category=self.category) shutil.copy(self.filepath, target_path) msg = "Imported `{}' as `{} / {}'".format(self.filepath, self.category, self.preset_name) - info(msg) + sv_logger.info(msg) self.report({'INFO'}, msg) return {'FINISHED'} @@ -734,13 +734,13 @@ class SvPresetFromGist(bpy.types.Operator): def execute(self, context): if not self.preset_name: msg = "Preset name is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} if not self.gist_id: msg = "Gist ID is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} @@ -748,7 +748,7 @@ def execute(self, context): target_path = get_preset_path(self.preset_name, category=self.category) if os.path.exists(target_path): msg = "Preset named `{}' already exists. Refusing to rewrite existing preset.".format(self.preset_name) - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} @@ -760,7 +760,7 @@ def execute(self, context): preset.make_add_operator() msg = "Imported `{}' as `{}'".format(self.gist_id, self.preset_name) - info(msg) + sv_logger.info(msg) self.report({'INFO'}, msg) return {'FINISHED'} @@ -787,17 +787,17 @@ def draw(self, context): def execute(self, context): if not self.category: msg = "Category name is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} if self.category == GENERAL or self.category in get_category_names(): msg = "Category named `{}' already exists; refusing to overwrite existing category" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} path = get_presets_directory(category = self.category, mkdir=True) - info("Created new category `%s' at %s", self.category, path) + sv_logger.info("Created new category `%s' at %s", self.category, path) self.report({'INFO'}, "Created new category {}".format(self.category)) return {'FINISHED'} @@ -818,12 +818,12 @@ class SvPresetCategoryDelete(bpy.types.Operator): def execute(self, context): if not self.category: msg = "Preset name is not specified" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} if self.category == GENERAL: msg = "General category can not be deleted" - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} @@ -831,7 +831,7 @@ def execute(self, context): files = glob(join(path, "*")) if files: msg = "Category `{}' is not empty; refusing to delete non-empty category.".format(self.category) - error(msg) + sv_logger.error(msg) self.report({'ERROR'}, msg) return {'CANCELLED'} os.rmdir(path) diff --git a/ui/profile_panel.py b/ui/profile_panel.py index af541c4f6d..6bb78a1cc8 100644 --- a/ui/profile_panel.py +++ b/ui/profile_panel.py @@ -8,7 +8,7 @@ import bpy from bpy.props import EnumProperty, BoolProperty -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger import sverchok.utils.profile as prof @@ -20,7 +20,7 @@ class SvProfilingToggle(bpy.types.Operator): def execute(self, context): prof.is_currently_enabled = not prof.is_currently_enabled - info("Profiling is set to %s", prof.is_currently_enabled) + sv_logger.info("Profiling is set to %s", prof.is_currently_enabled) return {'FINISHED'} @@ -81,7 +81,7 @@ class SvProfileReset(bpy.types.Operator): def execute(self, context): prof.reset_stats() - info("Profiling statistics data cleared.") + sv_logger.info("Profiling statistics data cleared.") return {'FINISHED'} diff --git a/ui/sv_IO_panel.py b/ui/sv_IO_panel.py index e7e938911c..29c56acb11 100644 --- a/ui/sv_IO_panel.py +++ b/ui/sv_IO_panel.py @@ -25,7 +25,7 @@ import bpy import sverchok -from sverchok.utils.logging import debug, info, warning, error, exception +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.sv_update_utils import version_and_sha from sverchok.utils import sv_gist_tools from sverchok.utils.sv_gist_tools import show_token_help, TOKEN_HELP_URL @@ -136,7 +136,7 @@ def execute(self, context): if destination_path.is_dir(): msg = 'folder was selected instead of file - didn\'t export' self.report({"WARNING"}, msg) - warning(msg) + sv_logger.warning(msg) return {'CANCELLED'} destination_path = destination_path.with_suffix('.json') @@ -145,7 +145,7 @@ def execute(self, context): if not layout_dict: msg = 'no update list found - didn\'t export' self.report({"WARNING"}, msg) - warning(msg) + sv_logger.warning(msg) return {'CANCELLED'} indent = None if self.compact else 2 @@ -153,7 +153,7 @@ def execute(self, context): json.dump(layout_dict, fpo, indent=indent) # json_struct doesn't expect sort_keys = True msg = 'exported to: ' + str(destination_path) self.report({"INFO"}, msg) - info(msg) + sv_logger.info(msg) if self.compress: comp_mode = zipfile.ZIP_DEFLATED @@ -162,7 +162,7 @@ def execute(self, context): with zipfile.ZipFile(archive_path, 'w', compression=comp_mode) as myzip: # need to specify arcname otherwise it'll copy the entire path myzip.write(destination_path, arcname=destination_path.name) - info('wrote: %s', archive_path.name) + sv_logger.info('wrote: %s', archive_path.name) return {'FINISHED'} @@ -304,8 +304,8 @@ def execute(self, context): gist_body = json.dumps(layout_dict, indent=2) # json_struct does not expect sort_keys = True except Exception as err: if 'not JSON serializable' in repr(err): - error(layout_dict) - exception(err) + sv_logger.error(layout_dict) + sv_logger.exception(err) self.report({'WARNING'}, "See terminal/Command prompt for printout of error") return {'CANCELLED'} @@ -320,13 +320,13 @@ def execute(self, context): return {'CANCELLED'} context.window_manager.clipboard = gist_url # full destination url - info(gist_url) + sv_logger.info(gist_url) self.report({'WARNING'}, "Copied gist URL to clipboard") sv_gist_tools.write_or_append_datafiles(gist_url, gist_filename) return {'FINISHED'} except Exception as err: - exception(err) + sv_logger.exception(err) self.report({'ERROR'}, "Error 222: net connection or github login failed!") return {'CANCELLED'} @@ -370,7 +370,7 @@ class SvBlendToArchive(bpy.types.Operator): def complete_msg(self, blend_archive_path): msg = 'saved current .blend as archive at ' + blend_archive_path self.report({'INFO'}, msg) - info(msg) + sv_logger.info(msg) def execute(self, context): diff --git a/ui/sv_extra_search.py b/ui/sv_extra_search.py index a4ab741b52..0dbeeab648 100644 --- a/ui/sv_extra_search.py +++ b/ui/sv_extra_search.py @@ -24,7 +24,7 @@ from bpy.props import StringProperty import sverchok -from sverchok.utils.logging import error +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.docstring import SvDocstring from sverchok.utils.sv_default_macros import macros, DefaultMacros from sverchok.ui.nodeview_space_menu import get_add_node_menu @@ -63,7 +63,7 @@ def ensure_valid_show_string(nodetype): description = nodetype.bl_rna.docstring.get_shorthand() return nodetype.bl_label + ensure_short_description(description) except Exception as err: - error(f'Nodetype "{nodetype}": ensure_valid_show_string() threw an exception:\n {err}') + sv_logger.error(f'Nodetype "{nodetype}": ensure_valid_show_string() threw an exception:\n {err}') def function_iterator(module_file): diff --git a/ui/sv_panel_display_nodes.py b/ui/sv_panel_display_nodes.py index 0dc3f75545..1e0264f4b4 100644 --- a/ui/sv_panel_display_nodes.py +++ b/ui/sv_panel_display_nodes.py @@ -21,7 +21,7 @@ from sverchok.utils.context_managers import sv_preferences from sverchok.settings import get_dpi_factor -from sverchok.utils.logging import debug +from sverchok.utils.sv_logging import sv_logger from collections import namedtuple from sverchok.ui.nodeview_space_menu import get_add_node_menu @@ -63,12 +63,12 @@ def __str__(self): def binpack(nodes, max_bin_height, spacing=0): ''' Add nodes to the bins of given max bin height and spacing ''' if nodes: - debug("There are %d nodes to bin pack" % (len(nodes))) + sv_logger.debug("There are %d nodes to bin pack" % (len(nodes))) for node in nodes: if node == None: - debug("WARNING: a None node in the spawned nodes???") + sv_logger.debug("WARNING: a None node in the spawned nodes???") else: - debug("WARNING: there are no nodes to bin pack!!!") + sv_logger.debug("WARNING: there are no nodes to bin pack!!!") return [] scale = 1.0 / get_dpi_factor() # dpi adjustment scale @@ -81,11 +81,11 @@ def binpack(nodes, max_bin_height, spacing=0): for n, bin in enumerate(bins): # check all the bins created so far if bin.height + len(bin.items) * spacing + item.height <= max_bin_height: # bin not full ? => add item - debug("ADDING node <%s> to bin #%d" % (item.name, n)) + sv_logger.debug("ADDING node <%s> to bin #%d" % (item.name, n)) bin.append(item) break # proceed to the next item else: # item didn't fit into any bin ? => add it to a new bin - debug('ADDING node <%s> to new bin' % (item.name)) + sv_logger.debug('ADDING node <%s> to new bin' % (item.name)) bin = Bin() bin.append(item) bins.append(bin) @@ -161,7 +161,7 @@ def add_spawned_node(context, name): if not _spawned_nodes: _spawned_nodes["main"] = [] - debug("ADDING spawned node: %s" % name) + sv_logger.debug("ADDING spawned node: %s" % name) tree = context.space_data.edit_tree @@ -182,14 +182,14 @@ def remove_spawned_nodes(context): tree = context.space_data.edit_tree - debug("There are %d previously spawned nodes to remove" % N) + sv_logger.debug("There are %d previously spawned nodes to remove" % N) for i, node in enumerate(nodes): try: if node != None: - debug("REMOVING spawned node %d of %d : %s" % (i+1, N, node.bl_idname)) + sv_logger.debug("REMOVING spawned node %d of %d : %s" % (i+1, N, node.bl_idname)) else: - debug("REMOVING spawned node %d of %d : None" % (i+1, N)) + sv_logger.debug("REMOVING spawned node %d of %d : None" % (i+1, N)) except: print("EXCEPTION: failed to remove spaned node (debug bad access)") @@ -236,7 +236,7 @@ class SvDisplayNodePanelProperties(bpy.types.PropertyGroup): def navigate_category(self, direction): ''' Navigate to PREV or NEXT category ''' - debug("Navigate to PREV or NEXT category") + sv_logger.debug("Navigate to PREV or NEXT category") categories = get_category_names() @@ -261,7 +261,7 @@ def arrange_nodes(self, context): try: nodes = get_spawned_nodes() - debug("ARRANGING %d nodes constrained by %s" % (len(nodes), self.constrain_layout)) + sv_logger.debug("ARRANGING %d nodes constrained by %s" % (len(nodes), self.constrain_layout)) scale = 1.0 / get_dpi_factor() # dpi adjustment scale @@ -290,12 +290,12 @@ def arrange_nodes(self, context): # add the spacing between bins totalWidth = totalWidth + self.grid_x_space * (len(bins)-1) - debug("{0} : min_h = {1:.2f} : max_h = {2:.2f}".format(num_steps, min_h, max_h)) - debug("For bin height = %d total width = %d (%d bins)" % (bin_height, totalWidth, len(bins))) + sv_logger.debug("{0} : min_h = {1:.2f} : max_h = {2:.2f}".format(num_steps, min_h, max_h)) + sv_logger.debug("For bin height = %d total width = %d (%d bins)" % (bin_height, totalWidth, len(bins))) delta = abs((self.grid_width - totalWidth)/self.grid_width) - debug("{0} : target = {1:.2f} : current = {2:.2f} : delta % = {3:.2f}".format( + sv_logger.debug("{0} : target = {1:.2f} : current = {2:.2f} : delta % = {3:.2f}".format( num_steps, self.grid_width, totalWidth, delta)) if delta < 0.1: # converged ? @@ -307,8 +307,8 @@ def arrange_nodes(self, context): else: # W > w (make h smaller) max_h = bin_height - debug("*** FOUND solution in %d steps" % num_steps) - debug("* {} bins of height {} : width {} : space {} ".format(len(bins), + sv_logger.debug("*** FOUND solution in %d steps" % num_steps) + sv_logger.debug("* {} bins of height {} : width {} : space {} ".format(len(bins), int(bin_height), int(totalWidth), (len(bins)-1)*self.grid_x_space @@ -335,14 +335,14 @@ def arrange_nodes(self, context): # add the spacing between bins totalWidth = totalWidth + self.grid_x_space * (len(bins)-1) - debug("{0} : min_h = {1:.2f} : max_h = {2:.2f}".format(num_steps, min_h, max_h)) - debug("For bin height = %d total width = %d" % (bin_height, totalWidth)) + sv_logger.debug("{0} : min_h = {1:.2f} : max_h = {2:.2f}".format(num_steps, min_h, max_h)) + sv_logger.debug("For bin height = %d total width = %d" % (bin_height, totalWidth)) current_aspect = totalWidth / bin_height delta_aspect = abs(current_aspect - target_aspect) - debug("{0} : target = {1:.2f} : current = {2:.2f} : delta = {3:.2f}".format( + sv_logger.debug("{0} : target = {1:.2f} : current = {2:.2f} : delta = {3:.2f}".format( num_steps, target_aspect, current_aspect, delta_aspect)) if delta_aspect < 0.1: # converged ? @@ -354,8 +354,8 @@ def arrange_nodes(self, context): else: # W/H > w/h (make h smaller) max_h = bin_height - debug("*** FOUND solution in %d steps" % num_steps) - debug("* {} bins of height {} : width {} : space {} ".format(len(bins), + sv_logger.debug("*** FOUND solution in %d steps" % num_steps) + sv_logger.debug("* {} bins of height {} : width {} : space {} ".format(len(bins), int(bin_height), int(totalWidth), (len(bins)-1)*self.grid_x_space @@ -380,7 +380,7 @@ def arrange_nodes(self, context): node.location[0] = x + 0.5 * (bin.width - node_width) node.location[1] = y - debug("node = {0:>{x}} : W, H ({1:.1f}, {2:.1f}) & X, Y ({3:.1f}, {4:.1f})".format( + sv_logger.debug("node = {0:>{x}} : W, H ({1:.1f}, {2:.1f}) & X, Y ({3:.1f}, {4:.1f})".format( node_name, node.dimensions.x * scale, node.dimensions.y * scale, node.location.x, node.location.y, @@ -399,12 +399,12 @@ def create_nodes(self, context): node_names = get_nodes_in_category(self.category) node_names.sort(reverse=False) - debug("* current category : %s" % self.category) - debug("* nodes in category : %s" % node_names) + sv_logger.debug("* current category : %s" % self.category) + sv_logger.debug("* nodes in category : %s" % node_names) N = len(node_names) - debug('There are <%d> nodes in category <%s>' % (N, self.category)) + sv_logger.debug('There are <%d> nodes in category <%s>' % (N, self.category)) if N == 0: return @@ -412,19 +412,19 @@ def create_nodes(self, context): for i, name in enumerate(node_names): cls = bpy.types.Node.bl_rna_get_subclass_py(name) if cls is None: - debug(f'Class of the "{name}" node was not found') + sv_logger.debug(f'Class of the "{name}" node was not found') continue if name == "separator": - debug("SKIPPING separator node") + sv_logger.debug("SKIPPING separator node") continue if cls.missing_dependency: - debug("SKIPPING dependent node %d of %d : %s" % (i+1, N, name)) + sv_logger.debug("SKIPPING dependent node %d of %d : %s" % (i+1, N, name)) continue if '@' in name: - debug("SKIPPING subcategory node: %s" % name) + sv_logger.debug("SKIPPING subcategory node: %s" % name) continue - debug("SPAWNING node %d of %d : %s" % (i+1, N, name)) + sv_logger.debug("SPAWNING node %d of %d : %s" % (i+1, N, name)) add_spawned_node(context, name) diff --git a/ui/testing_panel.py b/ui/testing_panel.py index 3c35252e67..084109c255 100644 --- a/ui/testing_panel.py +++ b/ui/testing_panel.py @@ -13,7 +13,7 @@ from sverchok import old_nodes from sverchok.utils.context_managers import sv_preferences from sverchok.utils.modules_inspection import iter_submodule_names -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger class SvRunTests(bpy.types.Operator): @@ -95,7 +95,7 @@ def execute(self, context): for node in ntree.nodes: if old_nodes.is_old(node): - info("Deprecated node: `%s' (%s)", node.name, node.bl_idname) + sv_logger.info("Deprecated node: `%s' (%s)", node.name, node.bl_idname) self.report({'INFO'}, "See logs") return {'FINISHED'} diff --git a/ui/text_editor_plugins.py b/ui/text_editor_plugins.py index 0e3231c6dc..f46d30c64b 100644 --- a/ui/text_editor_plugins.py +++ b/ui/text_editor_plugins.py @@ -6,7 +6,7 @@ # License-Filename: LICENSE import bpy -from sverchok.utils.logging import getLogger +from sverchok.utils.sv_logging import get_logger from sverchok.settings import get_params @@ -218,7 +218,7 @@ def register(): global logger bpy.utils.register_class(SvSNLiteAddFromTextEditor) bpy.utils.register_class(SvNodeRefreshFromTextEditor) - logger = getLogger("text_editor_plugins") + logger = get_logger() add_keymap() def unregister(): diff --git a/utils/adaptive_curve.py b/utils/adaptive_curve.py index f48f2b7aeb..50bb1dfc38 100644 --- a/utils/adaptive_curve.py +++ b/utils/adaptive_curve.py @@ -8,11 +8,11 @@ import numpy as np import numpy.random from math import ceil, floor, isnan -import random -from sverchok.utils.logging import debug, info, exception +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.math import distribute_int -from sverchok.utils.curve import SvCurve, SvCurveLengthSolver +from sverchok.utils.curve import SvCurveLengthSolver + class CurvePopulationController(object): def set_factors(self, factor_range, factors): @@ -104,7 +104,7 @@ def populate_curve(curve, samples_t, by_length = False, by_curvature = True, pop min_length = lengths.min() max_length = lengths.max() length_range = max_length - min_length - debug("Lengths range: %s - %s", min_length, max_length) + sv_logger.debug("Lengths range: %s - %s", min_length, max_length) if length_range == 0: lengths = np.zeros(samples_t - 1) else: @@ -123,7 +123,7 @@ def populate_curve(curve, samples_t, by_length = False, by_curvature = True, pop min_curvature = curvatures.min() max_curvature = curvatures.max() curvatures_range = max_curvature - min_curvature - debug("Curvatures range: %s - %s", min_curvature, max_curvature) + sv_logger.debug("Curvatures range: %s - %s", min_curvature, max_curvature) if curvatures_range == 0: curvatures = np.zeros(samples_t - 1) else: @@ -163,7 +163,7 @@ def populate_curve(curve, samples_t, by_length = False, by_curvature = True, pop t_r.append(t2) else: space = np.linspace(t1, t2, num=ppe, endpoint=True) - #debug("Space: %s - %s (%s): %s", t1, t2, ppe, space) + # sv_logger.debug("Space: %s - %s (%s): %s", t1, t2, ppe, space) t_r = space[1:].tolist() new_t.extend(t_r) diff --git a/utils/adaptive_surface.py b/utils/adaptive_surface.py index 04c794aa0f..47b3b3b680 100644 --- a/utils/adaptive_surface.py +++ b/utils/adaptive_surface.py @@ -14,8 +14,7 @@ except ImportError: delaunay_2d_cdt = None -from sverchok.utils.logging import info, exception -from sverchok.utils.surface import SvSurface +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.geom_2d.merge_mesh import crop_mesh_delaunay from sverchok.utils.voronoi import computeDelaunayTriangulation, Site @@ -82,7 +81,7 @@ def populate_surface_uv(surface, samples_u, samples_v, by_curvature=True, curvat max_curvature = max_curvatures.max() min_curvature = max_curvatures.min() curvatures_range = max_curvature - min_curvature - info("Curvature range: %s - %s", min_curvature, max_curvature) + sv_logger.info("Curvature range: %s - %s", min_curvature, max_curvature) if curvatures_range == 0: max_curvatures = np.zeros((samples_u-1, samples_v-1)) else: @@ -110,7 +109,7 @@ def populate_surface_uv(surface, samples_u, samples_v, by_curvature=True, curvat min_area = areas.min() max_area = areas.max() areas_range = max_area - min_area - info("Areas range: %s - %s", min_area, max_area) + sv_logger.info("Areas range: %s - %s", min_area, max_area) if areas_range == 0: areas = np.zeros((samples_u-1, samples_v-1)) else: @@ -127,9 +126,9 @@ def populate_surface_uv(surface, samples_u, samples_v, by_curvature=True, curvat max_factor = factors.max() if max_factor != 0: factors = factors / max_factor - #info("Factors: %s - %s (%s)", factors.min(), factors.max(), factor_range) - #info("Areas: %s - %s", areas.min(), areas.max()) - #info("Curvatures: %s - %s", max_curvatures.min(), max_curvatures.max()) + # sv_logger.info("Factors: %s - %s (%s)", factors.min(), factors.max(), factor_range) + # sv_logger.info("Areas: %s - %s", areas.min(), areas.max()) + # sv_logger.info("Curvatures: %s - %s", max_curvatures.min(), max_curvatures.max()) ppf_range = max_ppf - min_ppf @@ -152,8 +151,8 @@ def populate_surface_uv(surface, samples_u, samples_v, by_curvature=True, curvat #ppf = int(round(ppf)) ppf = ceil(ppf) # if ppf > 1: -# info("I %s, J %s, factor %s, PPF %s", i, j, factor, ppf) -# info("U %s - %s, V %s - %s", u1, u2, v1, v2) +# sv_logger.info("I %s, J %s, factor %s, PPF %s", i, j, factor, ppf) +# sv_logger.info("U %s - %s, V %s - %s", u1, u2, v1, v2) u_r = numpy.random.uniform(u1, u2, size=ppf).tolist() v_r = numpy.random.uniform(v1, v2, size=ppf).tolist() new_u.extend(u_r) diff --git a/utils/apidoc.py b/utils/apidoc.py index 9356bb695b..8990d0ad33 100644 --- a/utils/apidoc.py +++ b/utils/apidoc.py @@ -16,7 +16,7 @@ from os.path import join, dirname from os import makedirs -from sverchok.utils.logging import getLogger +from sverchok.utils.sv_logging import get_logger try: import pdoc @@ -53,7 +53,7 @@ def generate_api_documentation(root_directory, root_modules=None, logger=None): if pdoc is None: raise Exception("pdoc3 package is required in order to generate documentation") if logger is None: - logger = getLogger() + logger = get_logger() if not root_modules: root_modules = DEFAULT_MODULES logger.info(f"Start generating API documentation in {root_directory}") diff --git a/utils/ascii_print.py b/utils/ascii_print.py index 9e8dc3ea0b..7da8bf43c8 100644 --- a/utils/ascii_print.py +++ b/utils/ascii_print.py @@ -1,6 +1,5 @@ import os import sys -from sverchok.utils.development import get_version_string # pylint: disable=c0304 # pylint: disable=c0326 diff --git a/utils/curve/algorithms.py b/utils/curve/algorithms.py index fd63b5abf7..e7be6176d4 100644 --- a/utils/curve/algorithms.py +++ b/utils/curve/algorithms.py @@ -22,7 +22,7 @@ ZERO, FRENET, HOUSEHOLDER, TRACK, DIFF, TRACK_NORMAL, NORMAL_DIR, NONE ) -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger def make_euclidean_ts(pts): tmp = np.linalg.norm(pts[:-1] - pts[1:], axis=1) @@ -857,7 +857,7 @@ def concatenate_curves(curves, scale_to_unit=False, allow_generic=True): except UnsupportedCurveTypeException as e: exceptions.append(e) # "concatenate" method can't work with this type of curve - info("Can't natively join curve #%s (%s), will use generic method: %s", idx+1, curve, e) + sv_logger.info("Can't natively join curve #%s (%s), will use generic method: %s", idx+1, curve, e) # P.2: if some curves were already joined natively, # then we have to rescale each of other curves separately if some_native and scale_to_unit: diff --git a/utils/curve/bakery.py b/utils/curve/bakery.py index f121d9412c..281e14f80a 100644 --- a/utils/curve/bakery.py +++ b/utils/curve/bakery.py @@ -9,9 +9,9 @@ import bpy -from sverchok.utils.curve.core import UnsupportedCurveTypeException from sverchok.utils.curve.nurbs import SvNurbsCurve -from sverchok.utils.logging import getLogger +from sverchok.utils.sv_logging import get_logger + def curve_to_meshdata(curve, resolution): t_min, t_max = curve.get_u_bounds() @@ -35,7 +35,7 @@ def __init__(self, node, curve, resolution): self._nurbs_curve = None self.resolution = resolution - logger = getLogger("sverchok.utils.curve.bakery") + logger = get_logger() if node.draw_line or node.draw_verts or node.draw_comb or node.draw_curvature: t_min, t_max = curve.get_u_bounds() diff --git a/utils/curve/core.py b/utils/curve/core.py index cdf9f1cd04..10de901bee 100644 --- a/utils/curve/core.py +++ b/utils/curve/core.py @@ -10,14 +10,12 @@ """ import numpy as np -from math import sin, cos, pi, radians, sqrt from mathutils import Vector, Matrix -from sverchok.utils.geom import LineEquation, CubicSpline from sverchok.utils.integrate import TrapezoidIntegral -from sverchok.utils.logging import info, error -from sverchok.utils.math import binomial, binomial_array +from sverchok.utils.sv_logging import sv_logger +from sverchok.utils.math import binomial_array from sverchok.utils.nurbs_common import SvNurbsMaths, from_homogenous from sverchok.utils.curve import knotvector as sv_knotvector @@ -368,10 +366,10 @@ def frame_array(self, ts, on_zero_curvature=ASIS, tangent_delta=None): matrices_np = np.linalg.inv(matrices_np) return matrices_np, normals, binormals except np.linalg.LinAlgError as e: - error("Some of matrices are singular:") + sv_logger.error("Some of matrices are singular:") for i, m in enumerate(matrices_np): if abs(np.linalg.det(m) < 1e-5): - error("M[%s] (t = %s):\n%s", i, ts[i], m) + sv_logger.error("M[%s] (t = %s):\n%s", i, ts[i], m) raise e def zero_torsion_frame_array(self, ts, tangent_delta=None): diff --git a/utils/curve/freecad.py b/utils/curve/freecad.py index fa6bc00e7b..f49b7bc92c 100644 --- a/utils/curve/freecad.py +++ b/utils/curve/freecad.py @@ -15,7 +15,7 @@ from sverchok.utils.curve import knotvector as sv_knotvector from sverchok.utils.curve.primitives import SvLine, SvCircle from sverchok.utils.curve.biarc import SvBiArc -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger from sverchok.dependencies import FreeCAD if FreeCAD is not None: @@ -403,7 +403,7 @@ def curve_to_freecad(sv_curve): result.append(sv_curve) return result except UnsupportedCurveTypeException as e: - info(f"Can't convert {sv_curve} to native FreeCAD curve: {e}") + sv_logger.info(f"Can't convert {sv_curve} to native FreeCAD curve: {e}") pass return [curve_to_freecad_nurbs(sv_curve)] diff --git a/utils/curve/nurbs.py b/utils/curve/nurbs.py index 889e647351..96136bac9b 100644 --- a/utils/curve/nurbs.py +++ b/utils/curve/nurbs.py @@ -11,10 +11,8 @@ from copy import deepcopy import numpy as np -from math import pi, sqrt -import traceback +from math import pi -from sverchok.utils.logging import info from sverchok.utils.curve.core import SvCurve, SvTaylorCurve, UnsupportedCurveTypeException, calc_taylor_nurbs_matrices from sverchok.utils.curve.bezier import SvBezierCurve from sverchok.utils.curve import knotvector as sv_knotvector @@ -30,9 +28,8 @@ ) from sverchok.utils.surface.nurbs import SvNativeNurbsSurface, SvGeomdlSurface from sverchok.utils.surface.algorithms import nurbs_revolution_surface -from sverchok.utils.math import binomial_array, cmp from sverchok.utils.geom import bounding_box, LineEquation, are_points_coplanar, get_common_plane -from sverchok.utils.logging import getLogger +from sverchok.utils.sv_logging import get_logger, sv_logger from sverchok.dependencies import geomdl if geomdl is not None: @@ -73,7 +70,7 @@ def to_nurbs(cls, curve, implementation = NATIVE): try: return curve.to_nurbs(implementation = implementation) except UnsupportedCurveTypeException as e: - info("Can't convert %s to NURBS curve: %s", curve, e) + sv_logger.info("Can't convert %s to NURBS curve: %s", curve, e) pass return None @@ -369,7 +366,7 @@ def reduce_degree(self, delta=None, target=None, tolerance=1e-6, return_error=Fa return self if logger is None: - logger = getLogger() + logger = get_logger() def reduce_degree_once(curve, tolerance): if curve.is_bezier(): diff --git a/utils/curve/nurbs_algorithms.py b/utils/curve/nurbs_algorithms.py index b22d6cfb6f..fcee5cab1e 100644 --- a/utils/curve/nurbs_algorithms.py +++ b/utils/curve/nurbs_algorithms.py @@ -19,7 +19,7 @@ from sverchok.utils.curve.algorithms import unify_curves_degree, SvCurveLengthSolver, SvCurveFrameCalculator from sverchok.utils.curve.bezier import SvBezierCurve, SvCubicBezierCurve from sverchok.utils.decorators import deprecated -from sverchok.utils.logging import getLogger +from sverchok.utils.sv_logging import get_logger from sverchok.utils.math import ( ZERO, FRENET, HOUSEHOLDER, TRACK, DIFF, TRACK_NORMAL, NORMAL_DIR, NONE @@ -239,7 +239,7 @@ def intersect_segment_segment_mu(v1, v2, v3, v4, tolerance=1e-3): def _intersect_curves_line(curve1, curve2, precision=0.001, logger=None): if logger is None: - logger = getLogger() + logger = get_logger() t1_min, t1_max = curve1.get_u_bounds() t2_min, t2_max = curve2.get_u_bounds() @@ -260,7 +260,7 @@ def _intersect_curves_line(curve1, curve2, precision=0.001, logger=None): def _intersect_curves_equation(curve1, curve2, method='SLSQP', precision=0.001, logger=None): if logger is None: - logger = getLogger() + logger = get_logger() t1_min, t1_max = curve1.get_u_bounds() t2_min, t2_max = curve2.get_u_bounds() @@ -328,7 +328,7 @@ def _intersect_endpoints(segment1, segment2, tolerance=0.001): def intersect_nurbs_curves(curve1, curve2, method='SLSQP', numeric_precision=0.001, logger=None): if logger is None: - logger = getLogger() + logger = get_logger() u1_min, u1_max = curve1.get_u_bounds() u2_min, u2_max = curve2.get_u_bounds() diff --git a/utils/curve/nurbs_solver.py b/utils/curve/nurbs_solver.py index 8dfdf2a0b7..74c4a9eb13 100644 --- a/utils/curve/nurbs_solver.py +++ b/utils/curve/nurbs_solver.py @@ -39,7 +39,7 @@ import numpy as np from collections import defaultdict -from sverchok.utils.logging import getLogger +from sverchok.utils.sv_logging import get_logger from sverchok.utils.curve.core import SvCurve from sverchok.utils.curve import knotvector as sv_knotvector from sverchok.utils.nurbs_common import SvNurbsBasisFunctions, SvNurbsMaths, from_homogenous @@ -751,7 +751,7 @@ def solve_ex(self, problem_types = PROBLEM_ANY, implementation = SvNurbsMaths.NA self._init() if logger is None: - logger = getLogger() + logger = get_logger() residue = 0.0 ndim = self.ndim diff --git a/utils/decorators.py b/utils/decorators.py index 24fc09c38c..6b1c166ab2 100644 --- a/utils/decorators.py +++ b/utils/decorators.py @@ -20,7 +20,7 @@ import functools import inspect import warnings -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.ascii_print import str_color string_types = (type(b''), type(u'')) @@ -119,7 +119,7 @@ def wrapped(*args, **kwargs): msg = f"\n{func_name}: {duration}" # + display_args + display_kwargs try: - info(msg) + sv_logger.info(msg) except: print(msg) diff --git a/utils/field/probe.py b/utils/field/probe.py index 215fb34f58..4d7ca921ea 100644 --- a/utils/field/probe.py +++ b/utils/field/probe.py @@ -8,8 +8,7 @@ import random import numpy as np -from sverchok.utils.field.scalar import SvScalarField -from sverchok.utils.logging import error +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.kdtree import SvKdTree BATCH_SIZE = 50 @@ -83,7 +82,7 @@ def field_random_probe(field, bbox, count, while done < count: iterations += 1 if iterations > MAX_ITERATIONS: - error("Maximum number of iterations (%s) reached, stop.", MAX_ITERATIONS) + sv_logger.error("Maximum number of iterations (%s) reached, stop.", MAX_ITERATIONS) break batch_xs = [] batch_ys = [] diff --git a/utils/geom.py b/utils/geom.py index d651831594..f4f00661c3 100644 --- a/utils/geom.py +++ b/utils/geom.py @@ -30,10 +30,6 @@ import numpy as np from numpy import linalg from functools import wraps -import time - -import bpy -import bmesh import mathutils from mathutils import Matrix, Vector from mathutils.geometry import interpolate_bezier, intersect_line_line, intersect_point_line @@ -41,11 +37,9 @@ from sverchok.utils.modules.geom_primitives import ( circle, arc, quad, arc_slice, rect, grid, line) -from sverchok.utils.sv_bmesh_utils import bmesh_from_pydata -from sverchok.utils.sv_bmesh_utils import pydata_from_bmesh -from sverchok.data_structure import match_long_repeat, describe_data_shape -from sverchok.utils.math import np_mixed_product, np_dot -from sverchok.utils.logging import debug, info +from sverchok.data_structure import match_long_repeat +from sverchok.utils.math import np_mixed_product +from sverchok.utils.sv_logging import sv_logger # njit is a light-wrapper around numba.njit, if found from sverchok.dependencies import numba # not strictly needed i think... @@ -552,7 +546,7 @@ def normal(self, u, v, h=0.001): norm = np.linalg.norm(n) if norm != 0: n = n / norm - #debug("DU: {}, DV: {}, N: {}".format(du, dv, n)) + # sv_logger.debug("DU: {}, DV: {}, N: {}".format(du, dv, n)) result = tuple(n) self._normal_cache[(u,v)] = result return result @@ -572,7 +566,7 @@ def __init__(self, cyclic, vlist): self.acquire_lookup_table() self.get_buckets() # for idx, (k, v) in enumerate(sorted(self.lookup.items())): - # debug(k, v) + # sv_logger.debug(k, v) def find_bucket(self, factor): for bucket_min, bucket_max in zip(self.buckets[:-1], self.buckets[1:]): @@ -1177,7 +1171,7 @@ def intersect_with_plane(self, plane2): output: LineEquation or None, in case two planes are parallel. """ if self.is_parallel(plane2): - debug("{} is parallel to {}".format(self, plane2)) + sv_logger.debug("{} is parallel to {}".format(self, plane2)) return None direction = self.normal.cross(plane2.normal) diff --git a/utils/logging.py b/utils/logging.py deleted file mode 100644 index fd0c0fdf59..0000000000 --- a/utils/logging.py +++ /dev/null @@ -1,279 +0,0 @@ -from typing import Type, Dict - -import bpy - -import inspect -import traceback -import logging -import logging.handlers -from contextlib import contextmanager - -import sverchok -from sverchok.utils.development import get_version_string -from sverchok.utils.context_managers import sv_preferences -import sverchok.settings as settings - -# Hardcoded for now -log_format = "%(asctime)s.%(msecs)03d [%(levelname)s] %(name)s: %(message)s" - -# Whether logging to internal blender's text buffer is initialized -internal_buffer_initialized = False -# Whether logging to external text file is initialized -file_initialized = False -# Whether logging is initialized -initialized = False - - -@contextmanager -def catch_log_error(): - """Catch logging errors""" - try: - yield - except Exception as e: - frame, _, line, *_ = inspect.trace()[-1] - module = inspect.getmodule(frame) - name = module.__name__ or "" - try_initialize() - _logger = logging.getLogger(f'{name} {line}') - _logger.error(e) - if _logger.isEnabledFor(logging.DEBUG): - traceback.print_exc() - - -def log_error(err): - """Should be used in except statement""" - for frame, _, line, *_ in inspect.trace()[::-1]: - module = inspect.getmodule(frame) - if module is None: # looks like frame points into non Python module - continue # try to find the module before - else: - name = module.__name__ or "" - try_initialize() - _logger = logging.getLogger(f'{name}:{line} ') - _logger.error(err) - if _logger.isEnabledFor(logging.DEBUG): - traceback.print_exc() - break - - -@contextmanager -def fix_error_msg(msgs: Dict[Type[Exception], str]): - try: - yield - except Exception as e: - err_class = type(e) - if err_class in msgs: - e.args = (msgs[err_class], ) - raise - - -def get_log_buffer(log_buffer_name): - """ - Get internal blender text buffer for logging. - """ - try: - if log_buffer_name in bpy.data.texts: - return bpy.data.texts[log_buffer_name] - else: - return bpy.data.texts.new(name=log_buffer_name) - except AttributeError as e: - #logging.debug("Can't initialize logging to internal buffer: get_log_buffer is called too early: {}".format(e)) - return None - -class TextBufferHandler(logging.Handler): - """ - A handler class which writes logging records, appropriately formatted, - to Blender's internal text buffer. - """ - - terminator = '\n' - - def __init__(self, name): - """ - Initialize the handler. - """ - super().__init__() - self.buffer_name = name - - def emit(self, record): - """ - Emit a record. - If a formatter is specified, it is used to format the record. - The record is then written to the buffer with a trailing newline. If - exception information is present, it is formatted using - traceback.print_exception and appended to the stream. If the stream - has an 'encoding' attribute, it is used to determine how to do the - output to the stream. - """ - try: - msg = self.format(record) - stream = get_log_buffer(self.buffer_name) - if not stream: - print("Can't obtain buffer") - return - stream.write(msg) - stream.write(self.terminator) - self.flush() - except Exception: - self.handleError(record) - - def __repr__(self): - level = getLevelName(self.level) - name = getattr(self.stream, 'name', '') - if name: - name += ' ' - return '<%s %s(%s)>' % (self.__class__.__name__, name, level) - - -def try_initialize(): - """ - Try to initialize logging subsystem. - Does nothing if everything is already initialized. - Prints an error if it is called too early. - """ - global internal_buffer_initialized - global file_initialized - global initialized - - if sverchok.reload_event: - return - - with sv_preferences() as prefs: - if not prefs: - logging.error("Can't obtain logging preferences, it's too early. Stack:\n%s", "".join(traceback.format_stack())) - return - - if not internal_buffer_initialized: - if prefs.log_to_buffer: - buffer = get_log_buffer(prefs.log_buffer_name) - if buffer is not None: - handler = TextBufferHandler(prefs.log_buffer_name) - handler.setFormatter(logging.Formatter(log_format, datefmt="%Y-%m-%d %H:%M:%S")) - logging.getLogger().addHandler(handler) - - for area in bpy.context.screen.areas: - if area.type == 'TEXT_EDITOR': - if area.spaces[0].text is None: - area.spaces[0].text = buffer - break - internal_buffer_initialized = True - else: - internal_buffer_initialized = True - - if not file_initialized: - if prefs.log_to_file: - handler = logging.handlers.RotatingFileHandler(prefs.log_file_name, - maxBytes = 10*1024*1024, - backupCount = 3) - handler.setFormatter(logging.Formatter(log_format, datefmt="%Y-%m-%d %H:%M:%S")) - logging.getLogger().addHandler(handler) - - file_initialized = True - - if not initialized: - setLevel(prefs.log_level) - console_handler = logging.StreamHandler() - console_handler.setFormatter(logging.Formatter(log_format, datefmt='%H:%M:%S')) - logging.getLogger().addHandler(console_handler) - if not prefs.log_to_console: - # Remove console output handler. - logging.debug("Log output to console is disabled. Further messages will be available only in text buffer and file (if configured).") - logging.getLogger().removeHandler(console_handler) - - # https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library - logging.getLogger().addHandler(logging.NullHandler()) - - logging.info("Initializing Sverchok logging. Blender version %s, Sverchok version %s", bpy.app.version_string, get_version_string()) - logging.debug("Current log level: %s, log to text buffer: %s, log to file: %s, log to console: %s", - prefs.log_level, - ("no" if not prefs.log_to_buffer else prefs.log_buffer_name), - ("no" if not prefs.log_to_file else prefs.log_file_name), - ("yes" if prefs.log_to_console else "no")) - initialized = True - - -def clear_internal_buffer(): - """It clears only BLender text editor""" - with sv_preferences() as prefs: - if prefs.log_to_buffer_clean: - get_log_buffer(prefs.log_buffer_name).clear() - logging.debug("Internal text buffer cleared") - - -# Convenience functions - -def with_module_logger(method_name): - """ - Returns a method of Logger class instance. - Logger name is obtained from caller module name. - """ - def wrapper(*args, **kwargs): - if not is_enabled_for(method_name.upper()): - return - frame, _, line, *_ = inspect.stack()[1] - module = inspect.getmodule(frame) - name = module.__name__ or "" - try_initialize() - logger = logging.getLogger(f'{name} {line}') - method = getattr(logger, method_name) - return method(*args, **kwargs) - - wrapper.__name__ = method_name - wrapper.__doc__ = "Call `{}' method on a Logger. Logger name is obtained from caller module name.".format(method_name) - - return wrapper - -debug = with_module_logger("debug") -info = with_module_logger("info") -warning = with_module_logger("warning") -error = with_module_logger("error") -exception = with_module_logger("exception") - -def getLogger(name=None): - """ - Get Logger instance. - If name is None, then logger name is obtained from caller module name. - """ - if name is None: - frame, _, line, *_ = inspect.stack()[1] - module = inspect.getmodule(frame) - name = f'{module.__name__} {line}' - try_initialize() - return logging.getLogger(name) - -def setLevel(level): - """ - Set logging level for all handlers. - """ - if type(level) != int: - level = getattr(logging, level) - - logging.getLogger().setLevel(level) - for handler in logging.getLogger().handlers: - handler.setLevel(level) - - -def is_enabled_for(log_level="DEBUG") -> bool: - """This check should be used for improving performance of calling disabled loggers""" - addon = bpy.context.preferences.addons.get(sverchok.__name__) - current_level = getattr(logging, addon.preferences.log_level) - given_level = getattr(logging, log_level) - return given_level >= current_level - - -logger = logging.getLogger("logging") -settings.info = info -settings.setLevel = setLevel - -def register(): - global consoleHandler - - with sv_preferences() as prefs: - level = getattr(logging, prefs.log_level) - logger.info(f"log level, {level}") - logging.captureWarnings(True) - - -def unregister(): - logging.shutdown() - diff --git a/utils/manifolds.py b/utils/manifolds.py index 2869f2263a..32e026395e 100644 --- a/utils/manifolds.py +++ b/utils/manifolds.py @@ -4,9 +4,9 @@ from mathutils import kdtree from mathutils.bvhtree import BVHTree -from sverchok.utils.curve import SvCurve, SvIsoUvCurve +from sverchok.utils.curve import SvIsoUvCurve from sverchok.utils.curve.nurbs import SvNurbsCurve -from sverchok.utils.logging import debug, info, getLogger +from sverchok.utils.sv_logging import sv_logger, get_logger from sverchok.utils.geom import PlaneEquation, LineEquation, locate_linear from sverchok.dependencies import scipy @@ -98,7 +98,7 @@ def nearest_point_on_curve(src_points, curve, samples=10, precise=True, method=' Find nearest point on any curve. """ if logger is None: - logger = getLogger() + logger = get_logger() t_min, t_max = curve.get_u_bounds() @@ -663,7 +663,7 @@ def to_curve(point, curve, u1, u2, raycast=None): break step = np.linalg.norm(point - prev_point) if step < tolerance and i > 1: - debug("After ortho: Point {}, prev {}, iter {}".format(point, prev_point, i)) + sv_logger.debug("After ortho: Point {}, prev {}, iter {}".format(point, prev_point, i)) point_found = True break @@ -819,7 +819,7 @@ def intersect_curve_plane_ortho(curve, plane, init_samples=10, ortho_samples=10, point = ortho.nearest step = np.linalg.norm(point - prev_point) if step < tolerance: - debug("After ortho: Point {}, prev {}, iter {}".format(point, prev_point, i)) + sv_logger.debug("After ortho: Point {}, prev {}, iter {}".format(point, prev_point, i)) break prev_point = point @@ -833,7 +833,7 @@ def intersect_curve_plane_ortho(curve, plane, init_samples=10, ortho_samples=10, point = np.array(point) step = np.linalg.norm(point - prev_point) if step < tolerance: - debug("After raycast: Point {}, prev {}, iter {}".format(point, prev_point, i)) + sv_logger.debug("After raycast: Point {}, prev {}, iter {}".format(point, prev_point, i)) break prev_prev_point = prev_point @@ -990,7 +990,7 @@ def intersect_curve_plane(curve, plane, method = EQUATION, **kwargs): def curve_extremes(curve, field, samples=10, direction = 'MAX', on_fail = 'FAIL', logger=None): if logger is None: - logger = getLogger() + logger = get_logger() def goal(t): p = curve.evaluate(t) diff --git a/utils/modules/eval_formula.py b/utils/modules/eval_formula.py index 6ce41bbdbd..9e7d027ab7 100644 --- a/utils/modules/eval_formula.py +++ b/utils/modules/eval_formula.py @@ -19,7 +19,7 @@ import ast from sverchok.utils.script_importhelper import safe_names -from sverchok.utils import logging +from sverchok.utils import sv_logging class VariableCollector(ast.NodeVisitor): """ @@ -133,7 +133,7 @@ def safe_eval_compiled(compiled, variables, allowed_names = None): env["__builtins__"] = {} return eval(compiled, env) except SyntaxError as e: - logging.exception(e) + sv_logging.exception(e) raise Exception("Invalid expression syntax: " + str(e)) # It could be safer... diff --git a/utils/modules/matrix_utils.py b/utils/modules/matrix_utils.py index 9a1797c287..f78233afda 100644 --- a/utils/modules/matrix_utils.py +++ b/utils/modules/matrix_utils.py @@ -52,6 +52,6 @@ def matrix_apply_np(verts, matrix): verts should be a numpy array with shape (n,3) matrix can be a regular mathultis matrix''' - verts_co_4d = np.ones(shape=(verts.shape[0], 4), dtype=np.float) + verts_co_4d = np.ones(shape=(verts.shape[0], 4), dtype=np.float32) verts_co_4d[:, :-1] = verts # cos v (x,y,z,1) - point, v(x,y,z,0)- vector return np.einsum('ij,aj->ai', matrix, verts_co_4d)[:, :-1] diff --git a/utils/modules/profile_mk3/interpreter.py b/utils/modules/profile_mk3/interpreter.py index c253202cfe..b01d334ed1 100644 --- a/utils/modules/profile_mk3/interpreter.py +++ b/utils/modules/profile_mk3/interpreter.py @@ -23,13 +23,12 @@ from mathutils.geometry import interpolate_bezier from mathutils import Vector, Matrix -from sverchok.utils.logging import info, debug, warning +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.geom import interpolate_quadratic_bezier from sverchok.utils.sv_curve_utils import Arc from sverchok.utils.nurbs_common import SvNurbsMaths from sverchok.utils.curve import SvCircle, SvLine, SvBezierCurve, SvCubicBezierCurve import sverchok.utils.curve.knotvector as sv_knotvector -from sverchok.utils.curve.nurbs import SvNurbsCurve from sverchok.utils.curve.nurbs_solver import SvNurbsCurveControlPoints from sverchok.utils.curve.nurbs_solver_applications import prepare_solver_for_interpolation @@ -339,7 +338,7 @@ def interpret(self, interpreter, variables): v1 = (x, y0) interpreter.position = v1 verts = self._interpolate(v0, v1, num_segments) - #debug("V0 %s, v1 %s, N %s => %s", v0, v1, num_segments, verts) + # sv_logger.debug("V0 %s, v1 %s, N %s => %s", v0, v1, num_segments, verts) for vertex in verts[1:]: v_index = interpreter.new_vertex(*vertex) interpreter.new_edge(prev_index, v_index) @@ -1030,7 +1029,7 @@ def get_variables(self): def interpret(self, interpreter, variables): interpreter.assert_not_closed() if not interpreter.has_last_vertex: - info("X statement: no current point, do nothing") + sv_logger.info("X statement: no current point, do nothing") return v0 = interpreter.vertices[0] @@ -1064,7 +1063,7 @@ def get_variables(self): def interpret(self, interpreter, variables): interpreter.assert_not_closed() if not interpreter.has_last_vertex: - info("X statement: no current point, do nothing") + sv_logger.info("X statement: no current point, do nothing") return v0 = interpreter.vertices[interpreter.close_first_index] @@ -1263,6 +1262,6 @@ def interpret(self, profile, variables): if not profile: return for statement in profile: - debug("Interpret: %s", statement) + sv_logger.debug("Interpret: %s", statement) statement.interpret(self, variables) diff --git a/utils/modules/profile_mk3/parser.py b/utils/modules/profile_mk3/parser.py index 1d6ad56d04..9a9868b387 100644 --- a/utils/modules/profile_mk3/parser.py +++ b/utils/modules/profile_mk3/parser.py @@ -19,7 +19,7 @@ import re from sverchok.utils.parsec import * -from sverchok.utils.logging import info, debug, warning +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.modules.profile_mk3.interpreter import * ######################################### @@ -261,6 +261,6 @@ def parse_profile(src): cleaned = cleaned + " " + line profile = parse(parse_definition, cleaned) - debug(profile) + sv_logger.debug(profile) return profile diff --git a/utils/profile.py b/utils/profile.py index 434b000a8c..93959a2a22 100644 --- a/utils/profile.py +++ b/utils/profile.py @@ -20,7 +20,7 @@ import pstats from io import StringIO -from sverchok.utils.logging import info +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.context_managers import sv_preferences # Global cProfile.Profile singleton @@ -108,7 +108,7 @@ def dump_stats(sort = "tottime", strip_dirs = False, file_path=None): """ profile = get_global_profile() if not profile.getstats(): - info("There are no profiling results yet") + sv_logger.info("There are no profiling results yet") return if file_path is None: @@ -118,8 +118,8 @@ def dump_stats(sort = "tottime", strip_dirs = False, file_path=None): stats.strip_dirs() stats = stats.sort_stats(sort) stats.print_stats() - info("Profiling results:\n" + stream.getvalue()) - info("---------------------------") + sv_logger.info("Profiling results:\n" + stream.getvalue()) + sv_logger.info("---------------------------") else: with open(file_path, 'w') as stream: stats = pstats.Stats(profile, stream=stream) @@ -127,7 +127,7 @@ def dump_stats(sort = "tottime", strip_dirs = False, file_path=None): stats.strip_dirs() stats = stats.sort_stats(sort) stats.print_stats() - info("Profiling results are written to %s", file_path) + sv_logger.info("Profiling results are written to %s", file_path) def save_stats(path): """ @@ -136,11 +136,11 @@ def save_stats(path): """ profile = get_global_profile() if not profile.getstats(): - info("There are no profiling results yet") + sv_logger.info("There are no profiling results yet") return stats = pstats.Stats(profile) stats.dump_stats(path) - info("Profiling statistics saved to %s.", path) + sv_logger.info("Profiling statistics saved to %s.", path) def have_gathered_stats(): global _global_profile diff --git a/utils/quad_grid.py b/utils/quad_grid.py index 120f4470be..dcd59986cf 100644 --- a/utils/quad_grid.py +++ b/utils/quad_grid.py @@ -5,9 +5,6 @@ # SPDX-License-Identifier: GPL3 # License-Filename: LICENSE -import bmesh - -from sverchok.utils.logging import debug, info class SvQuadGridParser(object): """ diff --git a/utils/surface/algorithms.py b/utils/surface/algorithms.py index ed3bae6f8b..74a2f73b53 100644 --- a/utils/surface/algorithms.py +++ b/utils/surface/algorithms.py @@ -5,7 +5,6 @@ # SPDX-License-Identifier: GPL3 # License-Filename: LICENSE -import numpy as np from math import pi, cos, sin from collections import defaultdict @@ -21,7 +20,7 @@ autorotate_householder, autorotate_track, autorotate_diff, center, linear_approximation ) -from sverchok.utils.curve.core import SvFlipCurve, UnsupportedCurveTypeException +from sverchok.utils.curve.core import UnsupportedCurveTypeException from sverchok.utils.curve.primitives import SvCircle from sverchok.utils.curve import knotvector as sv_knotvector from sverchok.utils.curve.algorithms import ( @@ -33,7 +32,8 @@ from sverchok.utils.surface.nurbs import SvNurbsSurface from sverchok.utils.surface.data import * from sverchok.utils.nurbs_common import SvNurbsBasisFunctions, SvNurbsMaths -from sverchok.utils.logging import info, debug +from sverchok.utils.sv_logging import sv_logger + class SvInterpolatingSurface(SvSurface): __description__ = "Interpolating" @@ -855,7 +855,7 @@ def build(cls, curve1, curve2, vmin=0.0, vmax=1.0): # make_ruled_surface method can raise TypeError in case # it can't work with given curve2. # In this case we must use generic method. - debug("Can't make a native ruled surface: %s", e) + sv_logger.debug("Can't make a native ruled surface: %s", e) pass # generic method @@ -1164,7 +1164,7 @@ def concatenate_surfaces(direction, surfaces): result = result.concatenate(direction, s) return result except UnsupportedSurfaceTypeException as e: - debug("Can't concatenate surfaces natively: %s", e) + sv_logger.debug("Can't concatenate surfaces natively: %s", e) return SvConcatSurface(direction, surfaces) diff --git a/utils/surface/coons.py b/utils/surface/coons.py index 9b47027833..0efd24bace 100644 --- a/utils/surface/coons.py +++ b/utils/surface/coons.py @@ -7,8 +7,7 @@ import numpy as np -from sverchok.utils.logging import info, debug -from sverchok.utils.nurbs_common import from_homogenous +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.curve import knotvector as sv_knotvector from sverchok.utils.curve.core import UnsupportedCurveTypeException from sverchok.utils.curve.nurbs import SvNurbsCurve @@ -137,6 +136,6 @@ def coons_surface(curve1, curve2, curve3, curve4, use_nurbs=NURBS_IF_POSSIBLE): if use_nurbs == NURBS_ONLY: raise else: - info("Can't create a native Coons surface from curves %s: %s", curves, e) + sv_logger.info("Can't create a native Coons surface from curves %s: %s", curves, e) return SvCoonsSurface(*curves) diff --git a/utils/surface/core.py b/utils/surface/core.py index 38de04cf65..e93c0a02e2 100644 --- a/utils/surface/core.py +++ b/utils/surface/core.py @@ -5,13 +5,9 @@ # SPDX-License-Identifier: GPL3 # License-Filename: LICENSE -import numpy as np -from math import pi, cos, sin, atan, sqrt -from collections import defaultdict - -from sverchok.utils.logging import info, exception from sverchok.utils.surface.data import * + class UnsupportedSurfaceTypeException(TypeError): pass diff --git a/utils/surface/gordon.py b/utils/surface/gordon.py index ef9102b883..d6bc70694c 100644 --- a/utils/surface/gordon.py +++ b/utils/surface/gordon.py @@ -1,22 +1,13 @@ import numpy as np -from collections import defaultdict - -from sverchok.utils.geom import Spline -from sverchok.utils.nurbs_common import ( - SvNurbsMaths, SvNurbsBasisFunctions, - nurbs_divide, from_homogenous - ) -from sverchok.utils.curve import knotvector as sv_knotvector + from sverchok.utils.curve.bezier import SvBezierCurve -from sverchok.utils.curve.nurbs_algorithms import unify_curves, nurbs_curve_to_xoy, nurbs_curve_matrix -from sverchok.utils.curve.algorithms import unify_curves_degree, SvCurveFrameCalculator, curve_frame_on_surface_array +from sverchok.utils.curve.nurbs_algorithms import unify_curves +from sverchok.utils.curve.algorithms import unify_curves_degree, curve_frame_on_surface_array from sverchok.utils.curve.nurbs_solver_applications import interpolate_nurbs_curve_with_tangents -from sverchok.utils.surface.core import UnsupportedSurfaceTypeException -from sverchok.utils.surface import SvSurface, SurfaceCurvatureCalculator, SurfaceDerivativesData from sverchok.utils.surface.nurbs import SvNurbsSurface, simple_loft, interpolate_nurbs_surface from sverchok.utils.surface.algorithms import unify_nurbs_surfaces -from sverchok.utils.logging import getLogger -from sverchok.data_structure import repeat_last_for_length +from sverchok.utils.sv_logging import get_logger + def reparametrize_by_segments(curve, t_values, tolerance=1e-2): # Reparametrize given curve so that parameter values from t_values parameter @@ -86,7 +77,7 @@ def gordon_surface(u_curves, v_curves, intersections, metric='POINTS', u_knots=N raise Exception("Some of V-curves are rational. Rational curves are not supported for Gordon surface.") if logger is None: - logger = getLogger() + logger = get_logger() intersections = np.array(intersections) diff --git a/utils/surface/nurbs.py b/utils/surface/nurbs.py index 94124b28af..c8c3bb7395 100644 --- a/utils/surface/nurbs.py +++ b/utils/surface/nurbs.py @@ -14,7 +14,7 @@ from sverchok.utils.curve.nurbs_solver_applications import interpolate_nurbs_curve_with_tangents from sverchok.utils.surface.core import UnsupportedSurfaceTypeException from sverchok.utils.surface import SvSurface, SurfaceCurvatureCalculator, SurfaceDerivativesData -from sverchok.utils.logging import info, getLogger +from sverchok.utils.sv_logging import sv_logger, get_logger from sverchok.data_structure import repeat_last_for_length from sverchok.dependencies import geomdl @@ -54,7 +54,7 @@ def get(cls, surface, implementation = NATIVE): try: return surface.to_nurbs(implementation=implementation) except UnsupportedSurfaceTypeException as e: - info("Can't convert %s to NURBS: %s", surface, e) + sv_logger.info("Can't convert %s to NURBS: %s", surface, e) return None @classmethod @@ -284,7 +284,7 @@ def reduce_degree(self, direction, delta=None, target=None, tolerance=1e-6, logg return self if logger is None: - logger = getLogger() + logger = get_logger() implementation = self.get_nurbs_implementation() @@ -1170,7 +1170,7 @@ def simple_loft(curves, degree_v = None, knots_u = 'UNIFY', knotvector_accuracy= if knots_u not in {'UNIFY', 'AVERAGE'}: raise Exception(f"Unsupported knots_u option: {knots_u}") if logger is None: - logger = getLogger() + logger = get_logger() curves = unify_curves_degree(curves) if knots_u == 'UNIFY': curves = unify_curves(curves, accuracy=knotvector_accuracy) @@ -1240,7 +1240,7 @@ def loft_by_binormals(curves, degree_v = 3, logger = None): if logger is None: - logger = getLogger() + logger = get_logger() n_curves = len(curves) curves = unify_curves_degree(curves) @@ -1306,7 +1306,7 @@ def loft_with_tangents(curves, tangent_fields, degree_v = 3, logger = None): if logger is None: - logger = getLogger() + logger = get_logger() n_curves = len(curves) curves = unify_curves_degree(curves) @@ -1390,7 +1390,7 @@ def interpolate_nurbs_surface(degree_u, degree_v, points, metric='DISTANCE', ukn raise Exception("uknots and vknots must be either both provided or both omitted") if logger is None: - logger = getLogger() + logger = get_logger() if uknots is None: knots = np.array([Spline.create_knots(points[i,:], metric=metric) for i in range(n)]) diff --git a/utils/surface/populate.py b/utils/surface/populate.py index 1743bc48c4..8130e9fafb 100644 --- a/utils/surface/populate.py +++ b/utils/surface/populate.py @@ -10,9 +10,8 @@ from mathutils.kdtree import KDTree -from sverchok.utils.surface import SvSurface -from sverchok.utils.field.scalar import SvScalarField -from sverchok.utils.logging import error +from sverchok.utils.sv_logging import sv_logger + def random_point(min_x, max_x, min_y, max_y): x = random.uniform(min_x, max_x) @@ -110,7 +109,7 @@ def populate_surface(surface, field, count, threshold, while done < count: iterations += 1 if iterations > MAX_ITERATIONS: - error("Maximum number of iterations (%s) reached, stop.", MAX_ITERATIONS) + sv_logger.error("Maximum number of iterations (%s) reached, stop.", MAX_ITERATIONS) break batch_us = [] batch_vs = [] diff --git a/utils/surface/primitives.py b/utils/surface/primitives.py index 64057dcfec..6c8116e9da 100644 --- a/utils/surface/primitives.py +++ b/utils/surface/primitives.py @@ -6,11 +6,11 @@ # License-Filename: LICENSE import numpy as np -from sverchok.utils.logging import info, exception from sverchok.utils.surface.core import SvSurface from sverchok.utils.nurbs_common import SvNurbsMaths from sverchok.utils.curve import knotvector as sv_knotvector + class SvPlane(SvSurface): __description__ = "Plane" diff --git a/utils/sv_IO_panel_tools.py b/utils/sv_IO_panel_tools.py index 474969bcce..a8cf2fd057 100644 --- a/utils/sv_IO_panel_tools.py +++ b/utils/sv_IO_panel_tools.py @@ -22,7 +22,7 @@ import json import urllib -from sverchok.utils.logging import debug, info, warning, error, exception +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.sv_requests import urlopen # pylint: disable=w0621 @@ -43,10 +43,10 @@ def get_file_obj_from_zip(fullpath): break if not exported_name: - error('zip contains no files ending with .json') + sv_logger.error('zip contains no files ending with .json') return - debug(exported_name + ' <') + sv_logger.debug(exported_name + ' <') fp = jfile.open(exported_name, 'r') m = fp.read().decode() return json.loads(m) @@ -70,16 +70,16 @@ def read_n_decode(url): except urllib.error.HTTPError as err: if err.code == 404: message = 'url: ' + str(url) + ' doesn\'t appear to be a valid url, copy it again from your source' - error(message) + sv_logger.error(message) if operator: operator.report({'ERROR'}, message) else: message = 'url error:' + str(err.code) - error(message) + sv_logger.error(message) if operator: operator.report({'ERROR'}, message) except Exception as err: - exception(err) + sv_logger.exception(err) if operator: operator.report({'ERROR'}, 'unspecified error, check your internet connection') diff --git a/utils/sv_batch_primitives.py b/utils/sv_batch_primitives.py index 9df5f05a93..18de91d3f8 100644 --- a/utils/sv_batch_primitives.py +++ b/utils/sv_batch_primitives.py @@ -9,14 +9,14 @@ import gpu from gpu_extras.batch import batch_for_shader from mathutils import Matrix, Vector -from sverchok.utils.logging import info, error +from sverchok.utils.sv_logging import sv_logger if bpy.app.background: print("Will not initialize shaders in the background mode") class MatrixDraw28(object): def draw_matrix(self, *args, **kwargs): - info("draw_matrix: do nothing in background mode") + sv_logger.info("draw_matrix: do nothing in background mode") else: diff --git a/utils/sv_bmesh_utils.py b/utils/sv_bmesh_utils.py index 44510a8258..1923ce4113 100644 --- a/utils/sv_bmesh_utils.py +++ b/utils/sv_bmesh_utils.py @@ -29,7 +29,7 @@ import mathutils from sverchok.data_structure import zip_long_repeat, has_element -from sverchok.utils.logging import debug +from sverchok.utils.sv_logging import sv_logger @contextmanager def empty_bmesh(use_operators=True): @@ -254,7 +254,7 @@ def face_data_from_bmesh_faces(bm, face_data): for face in bm.faces: idx = face[initial_index] if idx < 0 or idx >= n_face_data: - debug("Unexisting face_data[%s] [0 - %s]", idx, n_face_data) + sv_logger.debug("Unexisting face_data[%s] [0 - %s]", idx, n_face_data) face_data_out.append(None) else: face_data_out.append(face_data[idx]) @@ -269,7 +269,7 @@ def edge_data_from_bmesh_edges(bm, edge_data): for edge in bm.edges: idx = edge[initial_index] if idx < 0 or idx >= n_edge_data: - debug("Unexisting edge_data[%s] [0 - %s]", idx, n_edge_data) + sv_logger.debug("Unexisting edge_data[%s] [0 - %s]", idx, n_edge_data) edge_data_out.append(None) else: edge_data_out.append(edge_data[idx]) @@ -284,7 +284,7 @@ def vert_data_from_bmesh_verts(bm, vert_data): for vert in bm.verts: idx = vert[initial_index] if idx < 0 or idx >= n_vert_data: - debug("Unexisting vert_data[%s] [0 - %s]", idx, n_vert_data) + sv_logger.debug("Unexisting vert_data[%s] [0 - %s]", idx, n_vert_data) vert_data_out.append(None) else: vert_data_out.append(vert_data[idx]) @@ -299,7 +299,7 @@ def bmesh_edges_from_edge_mask(bm, edge_mask): for bm_edge in bm.edges: idx = bm_edge[initial_index] if idx < 0 or idx >= n_edge_mask: - debug("Unexisting edge_mask[%s] [0 - %s]", idx, n_edge_mask) + sv_logger.debug("Unexisting edge_mask[%s] [0 - %s]", idx, n_edge_mask) else: mask = edge_mask[idx] if mask: @@ -762,7 +762,7 @@ def is_obstacle(face): other_face[path_distance] = new_distance other_face[path_prev_index] = face.index other_face[init_index] = face[init_index] - #debug("Front #%s: %s", step, len(new_wave_front)) + # sv_logger.debug("Front #%s: %s", step, len(new_wave_front)) done.update(wave_front) wave_front = new_wave_front @@ -835,7 +835,7 @@ def is_obstacle(vert): other_vert[path_distance] = new_distance other_vert[path_prev_index] = vert.index other_vert[init_index] = vert[init_index] - #debug("Front #%s: %s", step, len(new_wave_front)) + # sv_logger.debug("Front #%s: %s", step, len(new_wave_front)) done.update(wave_front) wave_front = new_wave_front diff --git a/utils/sv_gist_tools.py b/utils/sv_gist_tools.py index 9e67104ab7..f22b867020 100644 --- a/utils/sv_gist_tools.py +++ b/utils/sv_gist_tools.py @@ -18,13 +18,12 @@ import os import json -import base64 from time import gmtime, strftime from urllib.request import Request import webbrowser import bpy -from sverchok.utils.logging import info, debug, error +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.context_managers import sv_preferences from sverchok.utils.sv_requests import urlopen @@ -61,17 +60,17 @@ def upload_gist(): with sv_preferences() as prefs: token = prefs.github_token if not token: - info("GitHub API access token is not specified") + sv_logger.info("GitHub API access token is not specified") show_token_help() return - info("Uploading: %s", gist_filename) + sv_logger.info("Uploading: %s", gist_filename) headers = {"Authorization": "token " + token} req = Request(API_URL, data=json_post_data, headers=headers) json_to_parse = urlopen(req, data=json_post_data) - info('Received response from server') + sv_logger.info('Received response from server') found_json = json_to_parse.read().decode() return get_gist_url(found_json) diff --git a/utils/sv_json_import.py b/utils/sv_json_import.py index 1d7257f780..335f47481e 100644 --- a/utils/sv_json_import.py +++ b/utils/sv_json_import.py @@ -16,7 +16,7 @@ import bpy from sverchok import old_nodes from sverchok.utils.sv_IO_panel_tools import get_file_obj_from_zip -from sverchok.utils.logging import info, warning, getLogger, logging +from sverchok.utils.sv_logging import sv_logger, get_logger, logging from sverchok.utils.handle_blender_data import BPYProperty, BlNode from sverchok.utils.sv_json_struct import FileStruct, NodePresetFileStruct @@ -43,7 +43,7 @@ def init_from_path(cls, path: str) -> JSONImporter: structure = json.load(fp) return cls(structure) else: - warning(f'File should have .zip or .json extension, got ".{path.rsplit(".")[-1]}" instead') + sv_logger.warning(f'File should have .zip or .json extension, got ".{path.rsplit(".")[-1]}" instead') def import_into_tree(self, tree: SverchCustomTree, print_log: bool = True): """Import json structure into given tree and update it""" @@ -296,7 +296,7 @@ def add_fail(self, fail_name, source=None): yield except Exception as e: self._log[fail_name] += 1 - logger = getLogger() + logger = get_logger() if logger.isEnabledFor(logging.DEBUG): logger.debug(f'FAIL: "{fail_name}", {"SOURCE: " if source else ""}{source or ""}, {e}') traceback.print_exc() @@ -309,10 +309,10 @@ def has_fails(self) -> bool: def report_log_result(self): """Prints fails if their was or that they did not happen""" if self.has_fails: - warning(f'During import next fails has happened:') + sv_logger.warning(f'During import next fails has happened:') print(self.fail_message) else: - info(f'Import done with no fails') + sv_logger.info(f'Import done with no fails') @property def fail_message(self) -> str: diff --git a/utils/sv_logging.py b/utils/sv_logging.py new file mode 100644 index 0000000000..9e849af2dd --- /dev/null +++ b/utils/sv_logging.py @@ -0,0 +1,225 @@ +from pathlib import Path +from typing import Type, Dict, Optional + +import bpy + +import inspect +import traceback +import logging +import logging.handlers +from contextlib import contextmanager + +import sverchok + +if not sverchok.reload_event: # otherwise it leeds to infinite recursion + old_factory = logging.getLogRecordFactory() + + +def add_relative_path_factory(name, *args, **kwargs): + record = old_factory(name, *args, **kwargs) + if name.startswith('sverchok'): + path = Path(record.pathname) + + # search root path of the add-on + for root in path.parents: + if root.parent.name == 'addons': # add-ons are not always in the folder + break + else: + root = None + + if root is not None: + record.relative_path = path.relative_to(root) + else: # it can if there is several instances of sverchok (as add-on and a separate folder) + record.relative_path = path + return record + + +if not sverchok.reload_event: # otherwise it leeds to infinite recursion + logging.setLogRecordFactory(add_relative_path_factory) + +log_format = "%(asctime)s.%(msecs)03d [%(levelname)-5s] %(name)s %(relative_path)s:%(lineno)d - %(message)s" +sv_logger = logging.getLogger('sverchok') # root loger + +# set any level whatever you desire, +# it will be overridden by the add-on settings after the last one will be registered +if not sverchok.reload_event: + sv_logger.setLevel(logging.ERROR) + + +class ColorFormatter(logging.Formatter): + START_COLOR = '\033[{}m' + RESET_COLOR = '\033[0m' + COLORS = { + 'DEBUG': '1;30', # grey + 'INFO': 32, # green + 'WARNING': 33, # yellow + 'ERROR': 31, # red + 'CRITICAL': 41, # white on red bg + } + + def format(self, record): + color = self.START_COLOR.format(self.COLORS[record.levelname]) + color_format = color + self._fmt + self.RESET_COLOR + formatter = logging.Formatter(color_format, datefmt=self.datefmt) + return formatter.format(record) + + +console_handler = logging.StreamHandler() +console_handler.setFormatter(ColorFormatter(log_format, datefmt='%H:%M:%S')) +sv_logger.addHandler(console_handler) + + +def add_node_error_location(record: logging.LogRecord): + # https://docs.python.org/3/howto/logging-cookbook.html#using-filters-to-impart-contextual-information + # should be called with logger.error(msg, exc_info=True) + frame_info = inspect.getinnerframes(record.exc_info[-1])[-1] + record.relative_path = Path(frame_info.filename).name + record.lineno = frame_info.lineno + if not is_enabled_for('DEBUG'): # show traceback only in DEBUG mode + record.exc_info = None + return True + + +node_error_logger = logging.getLogger('sverchok.node_error') +node_error_logger.addFilter(add_node_error_location) + + +def add_file_handler(file_path): + sv_logger.debug(f'Logging to file="{file_path}"') + handler = logging.handlers.RotatingFileHandler(file_path, + maxBytes=10 * 1024 * 1024, + backupCount=3) + handler.setFormatter(logging.Formatter(log_format, datefmt="%Y-%m-%d %H:%M:%S")) + sv_logger.addHandler(handler) + + +def remove_console_handler(): + # Remove console output handler. + logging.debug("Log output to console is disabled. Further messages will" + " be available only in text buffer and file (if configured).") + sv_logger.removeHandler(console_handler) + # https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library + sv_logger.addHandler(logging.NullHandler()) + + +@contextmanager +def catch_log_error(): + """Catch logging errors""" + try: + yield + except Exception as e: + frame, _, line, *_ = inspect.trace()[-1] + module = inspect.getmodule(frame) + name = module.__name__ or "" + _logger = logging.getLogger(f'{name} {line}') + _logger.error(e) + if _logger.isEnabledFor(logging.DEBUG): + traceback.print_exc() + + +@contextmanager +def fix_error_msg(msgs: Dict[Type[Exception], str]): + try: + yield + except Exception as e: + err_class = type(e) + if err_class in msgs: + e.args = (msgs[err_class], ) + raise + + +class TextBufferHandler(logging.Handler): + """ + A handler class which writes logging records, appropriately formatted, + to Blender's internal text buffer. + """ + + terminator = '\n' + + def __init__(self, name): + """ + Initialize the handler. + """ + super().__init__() + self.buffer_name = name + if self.buffer is None: + raise RuntimeError("Can't create TextBufferHandler, " + "most likely because Blender is not fully loaded") + + def emit(self, record): + """ + Emit a record. + If a formatter is specified, it is used to format the record. + The record is then written to the buffer with a trailing newline. If + exception information is present, it is formatted using + traceback.print_exception and appended to the stream. If the stream + has an 'encoding' attribute, it is used to determine how to do the + output to the stream. + """ + # wen user enables a Sverchok extension it seems disables all Blender + # collections until the extension will be registered + # for now ignore such cases + if self.buffer is None: + return + + try: + msg = self.format(record) + self.buffer.write(msg) + self.buffer.write(self.terminator) + self.flush() + except Exception: + self.handleError(record) + + def clear(self): + """Clear all records""" + self.buffer.clear() + sv_logger.debug("Internal text buffer cleared") + + @property + def buffer(self) -> Optional: + """ + Get internal blender text buffer for logging. + """ + try: + return bpy.data.texts.get(self.buffer_name) \ + or bpy.data.texts.new(name=self.buffer_name) + except AttributeError as e: + # logging.debug("Can't initialize logging to internal buffer: get_log_buffer is called too early: {}".format(e)) + return None + + @classmethod + def add_to_main_logger(cls): + """This handler can work only after Blender is fully loaded""" + addon = bpy.context.preferences.addons.get(sverchok.__name__) + prefs = addon.preferences + if prefs.log_to_buffer: + sv_logger.debug(f'Logging to Blender text editor="{prefs.log_buffer_name}"') + handler = cls(prefs.log_buffer_name) + handler.setFormatter(logging.Formatter(log_format, datefmt="%Y-%m-%d %H:%M:%S")) + sv_logger.addHandler(handler) + + def __repr__(self): + level = logging.getLevelName(self.level) + name = getattr(self.buffer, 'name', '') + if name: + name += ' ' + return '<%s %s(%s)>' % (self.__class__.__name__, name, level) + + +# Convenience functions + + +def get_logger(): + """Get Logger instance. Logger name is obtained from caller module name.""" + frame, *_ = inspect.stack()[1] + module = inspect.getmodule(frame) + name = module.__name__ + return logging.getLogger(name) + + +def is_enabled_for(log_level="DEBUG") -> bool: + """This check should be used for improving performance of calling disabled loggers""" + addon = bpy.context.preferences.addons.get(sverchok.__name__) + current_level = getattr(logging, addon.preferences.log_level) + given_level = getattr(logging, log_level) + return given_level >= current_level diff --git a/utils/testing.py b/utils/testing.py index 0c44304c01..47969c111c 100644 --- a/utils/testing.py +++ b/utils/testing.py @@ -18,14 +18,33 @@ from sverchok.data_structure import get_data_nesting_level from sverchok.core.socket_data import get_output_socket_data from sverchok.core.sv_custom_exceptions import SvNoDataError -from sverchok.utils.logging import debug, info, setLevel from sverchok.utils.sv_json_import import JSONImporter + +sv_logger = logging.getLogger('sverchok.testing') + + +@contextmanager +def only_test_logs(): + def filter_test_logs(record: logging.LogRecord): + """Turnoff all other than test logs""" + return record.name.startswith('sverchok.testing') + + root_loger = logging.getLogger('sverchok') + for handler in root_loger.handlers: + handler.addFilter(filter_test_logs) + try: + yield + finally: + for handler in root_loger.handlers: + handler.removeFilter(filter_test_logs) + + try: import coverage coverage_available = True except ImportError: - #info("Coverage module is not installed") + # sv_logger.info("Coverage module is not installed") coverage_available = False ########################################## @@ -94,8 +113,10 @@ def create_node_tree(name=None, must_not_exist=True): if must_not_exist: if name in bpy.data.node_groups: raise Exception("Will not create tree `{}': it already exists".format(name)) - debug("Creating tree: %s", name) - return bpy.data.node_groups.new(name=name, type="SverchCustomTreeType") + sv_logger.debug("Creating tree: %s", name) + tree = bpy.data.node_groups.new(name=name, type="SverchCustomTreeType") + tree.sv_process = False # turn off auto processing tree by default + return tree def get_or_create_node_tree(name=None): """ @@ -104,7 +125,7 @@ def get_or_create_node_tree(name=None): if name is None: name = "TestingTree" if name in bpy.data.node_groups: - debug("Using existing tree: %s", name) + sv_logger.debug("Using existing tree: %s", name) return bpy.data.node_groups[name] else: return create_node_tree(name) @@ -116,7 +137,7 @@ def get_node_tree(name=None): if name is None: name = "TestingTree" if name in bpy.data.node_groups: - debug("Using existing tree: %s", name) + sv_logger.debug("Using existing tree: %s", name) return bpy.data.node_groups[name] else: raise Exception("There is no node tree named `{}'".format(name)) @@ -134,7 +155,7 @@ def remove_node_tree(name=None): if len(areas): space = areas[0].spaces[0] space.node_tree = None - debug("Removing tree: %s", name) + sv_logger.debug("Removing tree: %s", name) tree = bpy.data.node_groups[name] bpy.data.node_groups.remove(tree) @@ -157,7 +178,7 @@ def link_node_tree(reference_blend_path, tree_name=None): if tree_name in bpy.data.node_groups: raise Exception("Tree named `{}' already exists in current scene".format(tree_name)) with bpy.data.libraries.load(reference_blend_path, link=True) as (data_src, data_dst): - info(f"---- Linked node tree: {basename(reference_blend_path)}") + sv_logger.debug(f"---- Linked node tree: {basename(reference_blend_path)}") data_dst.node_groups = [tree_name] # right here the update method of the imported tree will be called # sverchok does not have a way of preventing this update @@ -170,7 +191,7 @@ def link_text_block(reference_blend_path, block_name): """ with bpy.data.libraries.load(reference_blend_path, link=True) as (data_src, data_dst): - info(f"---- Linked text block: {basename(reference_blend_path)}") + sv_logger.debug(f"---- Linked text block: {basename(reference_blend_path)}") data_dst.texts = [block_name] def create_node(node_type, tree_name=None): @@ -179,7 +200,7 @@ def create_node(node_type, tree_name=None): """ if tree_name is None: tree_name = "TestingTree" - debug("Creating node of type %s", node_type) + sv_logger.debug("Creating node of type %s", node_type) return bpy.data.node_groups[tree_name].nodes.new(type=node_type) def get_node(node_name, tree_name=None): @@ -210,7 +231,7 @@ def run_all_tests(pattern=None, log_file = 'sverchok_tests.log', log_level = Non pattern = "*_tests.py" if log_level is not None: - setLevel(log_level) + sv_logger.setLevel(log_level) tests_path = get_tests_path() log_handler = logging.FileHandler(join(tests_path, log_file), mode='w') @@ -221,9 +242,11 @@ def run_all_tests(pattern=None, log_file = 'sverchok_tests.log', log_level = Non buffer = StringIO() runner = unittest.TextTestRunner(stream = buffer, verbosity=verbosity, failfast=failfast) old_nodes.register_all() - with coverage_report(): + with coverage_report(), only_test_logs(): + sv_logger.warning("Run all tests with log level=[%s]", + logging.getLevelName(sv_logger.getEffectiveLevel())) result = runner.run(suite) - info("Test cases result:\n%s", buffer.getvalue()) + sv_logger.info("Test cases result:\n%s", buffer.getvalue()) return result finally: logging.getLogger().removeHandler(log_handler) @@ -246,7 +269,7 @@ def run_test_from_file(file_name): runner = unittest.TextTestRunner(stream=buffer, verbosity=2) old_nodes.register_all() result = runner.run(suite) - info("Test cases result:\n%s", buffer.getvalue()) + sv_logger.info("Test cases result:\n%s", buffer.getvalue()) return result finally: logging.getLogger().removeHandler(log_handler) @@ -269,7 +292,7 @@ class SverchokTestCase(unittest.TestCase): """ def setUp(self): - debug("Starting test: %s", self.__class__.__name__) + sv_logger.debug("Starting test: %s", self.id()) @contextmanager def temporary_node_tree(self, new_tree_name): @@ -515,8 +538,8 @@ def compare(prev_indicies, item1, item2): def assert_sverchok_data_equals_file(self, data, expected_data_file_name, precision=None): expected_data = self.load_reference_sverchok_data(expected_data_file_name) - #info("Data: %s", data) - #info("Expected data: %s", expected_data) + # sv_logger.info("Data: %s", data) + # sv_logger.info("Expected data: %s", expected_data) self.assert_sverchok_data_equal(data, expected_data, precision=precision) #self.assertEquals(data, expected_data) @@ -566,7 +589,7 @@ def assert_logs_no_errors(self): Usage: with self.assert_logs_no_errors(): - info("this is just an information, not error") + sv_logger.info("this is just an information, not error") """ @@ -582,11 +605,11 @@ def emit(self, record): logging.getLogger().addHandler(handler) try: - debug("=== \/ === [%s] Here should be no errors === \/ ===", self.__class__.__name__) + sv_logger.debug("=== \/ === [%s] Here should be no errors === \/ ===", self.__class__.__name__) yield handler self.assertFalse(has_errors, "There were some errors logged") finally: - debug("=== /\ === [%s] There should be no errors === /\ ===", self.__class__.__name__) + sv_logger.debug("=== /\ === [%s] There should be no errors === /\ ===", self.__class__.__name__) logging.getLogger().handlers.remove(handler) def subtest_assert_equals(self, value1, value2, message=None): @@ -859,6 +882,6 @@ def requires(module): raise Exception("Some tests failed") sys.exit(0) except Exception as e: - print(e) + sv_logger.exception(e) sys.exit(1) diff --git a/utils/turtle.py b/utils/turtle.py index 109a372ea1..f86d64deeb 100644 --- a/utils/turtle.py +++ b/utils/turtle.py @@ -17,10 +17,9 @@ # ##### END GPL LICENSE BLOCK ##### from collections import defaultdict -import bmesh -import mathutils -from sverchok.utils.logging import debug +from sverchok.utils.sv_logging import sv_logger + class Turtle(object): """ @@ -189,7 +188,7 @@ def click(self): self.current_loop = next_loop self.current_face = next_loop.face - debug("Current face # := %s", self.current_face.index) + sv_logger.debug("Current face # := %s", self.current_face.index) if self.selection_mode == self.MASK: if not self.selection_mask: @@ -221,7 +220,7 @@ def click(self): self.painting_index[painting_layer.name] = (self.painting_index[painting_layer.name] + 1) % n value = painting_mask[self.painting_index[painting_layer.name]] self.current_face[painting_layer] = value - debug("Paint face #%s, layer `%s' with value `%s'", self.current_face.index, painting_layer.name, value) + sv_logger.debug("Paint face #%s, layer `%s' with value `%s'", self.current_face.index, painting_layer.name, value) def get_opposite_loop(self, loop, bias=None): """ @@ -487,21 +486,21 @@ def select(self): Mark the current face as selected. """ self.current_face.select = True - debug("Selecting face #%s", self.current_face.index) + sv_logger.debug("Selecting face #%s", self.current_face.index) def unselect(self): """ Mark the current face as not selected. """ self.current_face.select = False - debug("Unselecting face #%s", self.current_face.index) + sv_logger.debug("Unselecting face #%s", self.current_face.index) def toggle(self): """ Toggle the selection state of the current face. """ self.current_face.select = not self.current_face.select - debug("Set face #%s selection := %s", self.current_face.index, self.current_face.select) + sv_logger.debug("Set face #%s selection := %s", self.current_face.index, self.current_face.select) def start_selecting(self, mode = None, mask=None): """ diff --git a/utils/voronoi.py b/utils/voronoi.py index 3d870c6999..9de325fa47 100644 --- a/utils/voronoi.py +++ b/utils/voronoi.py @@ -102,8 +102,6 @@ def usage(): # ############################################################################# import math -import sys -import getopt import numpy as np from math import sqrt, atan2 @@ -115,7 +113,7 @@ def usage(): from mathutils.bvhtree import BVHTree from mathutils.kdtree import KDTree -from sverchok.utils.logging import debug, info, error +from sverchok.utils.sv_logging import sv_logger from sverchok.utils.geom import center, LineEquation2D, CircleEquation2D from sverchok.utils.math import weighted_center from sverchok.utils.sv_bmesh_utils import pydata_from_bmesh, bmesh_from_pydata @@ -1227,7 +1225,7 @@ def voronoi_bounded(sites, bound_mode='BOX', clip=True, draw_bounds=True, draw_h new_vert_idx = bm.new_vert(tuple(v)) bounding_verts.append(new_vert_idx) else: - error("unexpected number of intersections of infinite line %s with area bounds %s: %s", eqn, bounds, intersections) + sv_logger.error("unexpected number of intersections of infinite line %s with area bounds %s: %s", eqn, bounds, intersections) # TODO: there could be (finite) edges, which have both ends # outside of the bounding line. We could detect such edges and