| 1 |
Logging |
| 2 |
======= |
| 3 |
|
| 4 |
Schedule logs messages to the Python logger named ``schedule`` at ``DEBUG`` level. |
| 5 |
To receive logs from Schedule, set the logging level to ``DEBUG``. |
| 6 |
|
| 7 |
.. code-block:: python |
| 8 |
|
| 9 |
import schedule |
| 10 |
import logging |
| 11 |
|
| 12 |
logging.basicConfig() |
| 13 |
schedule_logger = logging.getLogger('schedule') |
| 14 |
schedule_logger.setLevel(level=logging.DEBUG) |
| 15 |
|
| 16 |
def job(): |
| 17 |
print("Hello, Logs") |
| 18 |
|
| 19 |
schedule.every().second.do(job) |
| 20 |
|
| 21 |
schedule.run_all() |
| 22 |
|
| 23 |
schedule.clear() |
| 24 |
|
| 25 |
This will result in the following log messages: |
| 26 |
|
| 27 |
.. code-block:: text |
| 28 |
|
| 29 |
DEBUG:schedule:Running *all* 1 jobs with 0s delay in between |
| 30 |
DEBUG:schedule:Running job Job(interval=1, unit=seconds, do=job, args=(), kwargs={}) |
| 31 |
Hello, Logs |
| 32 |
DEBUG:schedule:Deleting *all* jobs |
| 33 |
|
| 34 |
|
| 35 |
Customize logging |
| 36 |
----------------- |
| 37 |
The easiest way to add reusable logging to jobs is to implement a decorator that handles logging. |
| 38 |
As an example, below code adds the ``print_elapsed_time`` decorator: |
| 39 |
|
| 40 |
.. code-block:: python |
| 41 |
|
| 42 |
import functools |
| 43 |
import time |
| 44 |
import schedule |
| 45 |
|
| 46 |
# This decorator can be applied to any job function to log the elapsed time of each job |
| 47 |
def print_elapsed_time(func): |
| 48 |
@functools.wraps(func) |
| 49 |
def wrapper(*args, **kwargs): |
| 50 |
start_timestamp = time.time() |
| 51 |
print('LOG: Running job "%s"' % func.__name__) |
| 52 |
result = func(*args, **kwargs) |
| 53 |
print('LOG: Job "%s" completed in %d seconds' % (func.__name__, time.time() - start_timestamp)) |
| 54 |
return result |
| 55 |
|
| 56 |
return wrapper |
| 57 |
|
| 58 |
|
| 59 |
@print_elapsed_time |
| 60 |
def job(): |
| 61 |
print('Hello, Logs') |
| 62 |
time.sleep(5) |
| 63 |
|
| 64 |
schedule.every().second.do(job) |
| 65 |
|
| 66 |
schedule.run_all() |
| 67 |
|
| 68 |
This outputs: |
| 69 |
|
| 70 |
.. code-block:: text |
| 71 |
|
| 72 |
LOG: Running job "job" |
| 73 |
Hello, Logs |
| 74 |
LOG: Job "job" completed in 5 seconds |