Skip to content

Commit

Permalink
Merge pull request #1497 from dreusel/scoped-logging
Browse files Browse the repository at this point in the history
Use scoped logging
  • Loading branch information
falkoschindler authored Aug 28, 2023
2 parents 843998a + ebc18c4 commit 915080b
Show file tree
Hide file tree
Showing 5 changed files with 15 additions and 16 deletions.
4 changes: 2 additions & 2 deletions nicegui/binding.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import asyncio
import logging
import time
from collections import defaultdict
from collections.abc import Mapping
Expand Down Expand Up @@ -46,7 +45,8 @@ async def loop() -> None:
propagate(target_obj, target_name, visited)
del link, source_obj, target_obj # pylint: disable=modified-iterating-list
if time.time() - t > MAX_PROPAGATION_TIME:
logging.warning(f'binding propagation for {len(active_links)} active links took {time.time() - t:.3f} s')
globals.log.warning(
f'binding propagation for {len(active_links)} active links took {time.time() - t:.3f} s')
await asyncio.sleep(globals.binding_refresh_interval)


Expand Down
4 changes: 2 additions & 2 deletions nicegui/native.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import asyncio
import inspect
import logging
import warnings
from dataclasses import dataclass, field
from functools import partial
from multiprocessing import Queue
from typing import Any, Callable, Dict, Optional, Tuple

from .globals import log
from .helpers import KWONLY_SLOTS

method_queue: Queue = Queue()
Expand Down Expand Up @@ -120,7 +120,7 @@ def wrapper(*args: Any, **kwargs: Any) -> Any:
method_queue.put((name, args, kwargs))
return response_queue.get() # wait for the method to be called and writing its result to the queue
except Exception:
logging.exception(f'error in {name}')
log.exception(f'error in {name}')
name = inspect.currentframe().f_back.f_code.co_name # type: ignore
return await asyncio.get_event_loop().run_in_executor(None, partial(wrapper, *args, **kwargs))

Expand Down
13 changes: 6 additions & 7 deletions nicegui/native_mode.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import _thread
import logging
import multiprocessing as mp
import queue
import socket
Expand Down Expand Up @@ -57,7 +56,7 @@ def execute(method: Callable, args: Tuple[Any, ...], kwargs: Dict[str, Any]) ->
if response is not None or 'dialog' in method.__name__:
response_queue.put(response)
except Exception:
logging.exception(f'error in window.{method.__name__}')
globals.log.exception(f'error in window.{method.__name__}')

def window_method_executor() -> None:
pending_executions: List[Thread] = []
Expand All @@ -66,7 +65,7 @@ def window_method_executor() -> None:
method_name, args, kwargs = method_queue.get(block=False)
if method_name == 'signal_server_shutdown':
if pending_executions:
logging.warning('shutdown is possibly blocked by opened dialogs like a file picker')
globals.log.warning('shutdown is possibly blocked by opened dialogs like a file picker')
while pending_executions:
pending_executions.pop().join()
elif method_name == 'get_always_on_top':
Expand All @@ -83,11 +82,11 @@ def window_method_executor() -> None:
pending_executions.append(Thread(target=execute, args=(method, args, kwargs)))
pending_executions[-1].start()
else:
logging.error(f'window.{method_name} is not callable')
globals.log.error(f'window.{method_name} is not callable')
except queue.Empty:
time.sleep(0.01)
except Exception:
logging.exception(f'error in window.{method_name}')
globals.log.exception(f'error in window.{method_name}')

Thread(target=window_method_executor).start()

Expand All @@ -102,8 +101,8 @@ def check_shutdown() -> None:
_thread.interrupt_main()

if 'native' not in globals.optional_features:
logging.error('Native mode is not supported in this configuration.\n'
'Please run "pip install pywebview" to use it.')
globals.log.error('Native mode is not supported in this configuration.\n'
'Please run "pip install pywebview" to use it.')
sys.exit(1)

mp.freeze_support()
Expand Down
5 changes: 2 additions & 3 deletions nicegui/run.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import logging
import multiprocessing
import os
import socket
Expand Down Expand Up @@ -123,7 +122,7 @@ def run(*,
return

if reload and not hasattr(__main__, '__file__'):
logging.warning('auto-reloading is only supported when running from a file')
globals.log.warning('auto-reloading is only supported when running from a file')
globals.reload = reload = False

if fullscreen:
Expand Down Expand Up @@ -170,7 +169,7 @@ def split_args(args: str) -> List[str]:
globals.server = Server(config=config)

if (reload or config.workers > 1) and not isinstance(config.app, str):
logging.warning('You must pass the application as an import string to enable "reload" or "workers".')
globals.log.warning('You must pass the application as an import string to enable "reload" or "workers".')
sys.exit(1)

if config.should_reload:
Expand Down
5 changes: 3 additions & 2 deletions prometheus.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import inspect
import logging
import uuid

from fastapi import FastAPI, Request, Response
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint

from nicegui.globals import log

EXCLUDED_USER_AGENTS = {'bot', 'spider', 'crawler', 'monitor', 'curl',
'wget', 'python-requests', 'kuma', 'health check'}

Expand All @@ -13,7 +14,7 @@ def start_monitor(app: FastAPI) -> None:
try:
import prometheus_client
except ModuleNotFoundError:
logging.info('Prometheus not installed, skipping monitoring')
log.info('Prometheus not installed, skipping monitoring')
return

visits = prometheus_client.Counter('nicegui_page_visits', 'Number of real page visits',
Expand Down

0 comments on commit 915080b

Please sign in to comment.