1
0
mirror of https://github.com/otter18/tg_logger.git synced 2025-08-04 21:32:56 +02:00

56 Commits
v1.0.1 ... main

Author SHA1 Message Date
ChernV
69c60badbf Merge pull request #6 from otter18/beta
version 3.3
2021-12-31 10:32:50 +03:00
ChernV
1ebbc9e3ac version 3.3 2021-12-31 10:31:39 +03:00
ChernV
ce7560ef22 README.md fix 2021-11-06 18:04:41 +03:00
ChernV
91e2d68f86 version 3.2-beta 2021-11-06 18:01:10 +03:00
ChernV
66d5c20105 flask example fix 2021-03-28 21:24:56 +03:00
ChernV
919539e7f7 intro_img added 2021-03-27 17:38:42 +03:00
ChernV
8c5038a878 Add files via upload 2021-03-27 17:36:04 +03:00
ChernV
122cda5252 Update README.md 2021-03-26 14:19:06 +03:00
ChernV
42f8ed3c5c Add files via upload 2021-03-24 18:06:04 +03:00
ChernV
a493cca053 Update README.md 2021-03-17 18:13:16 +03:00
ChernV
de3526bb87 Update README.md 2021-03-17 08:47:15 +03:00
ChernV
f6066abc43 Update index.rst 2021-03-13 15:11:45 +03:00
ChernV
159c18826d Update fqa.rst 2021-03-13 15:09:11 +03:00
ChernV
74fd1c4fa2 Update README.md 2021-03-13 15:04:35 +03:00
ChernV
09977fbac0 Update README.md 2021-03-13 15:03:53 +03:00
ChernV
882fdc4ad0 Update README.md 2021-03-13 15:00:50 +03:00
ChernV
edbbdac6e4 Update README.md 2021-03-12 19:44:19 +03:00
ChernV
e6833597a6 Update conf.py 2021-03-11 20:42:48 +03:00
Chernykh Vladimir
63d00bad8d Merge remote-tracking branch 'origin/main' into main 2021-03-11 20:41:11 +03:00
Chernykh Vladimir
698b79eb54 v3.1 docs fix 2021-03-11 20:40:57 +03:00
ChernV
1d851a1a59 Update modules.rst 2021-03-11 20:33:36 +03:00
Chernykh Vladimir
58c1d027f2 v3.1 2021-03-11 20:28:48 +03:00
ChernV
70eaa754bf Update modules.rst 2021-03-11 19:58:51 +03:00
ChernV
56fe5a07b7 docs shield 2021-03-11 19:50:57 +03:00
Chernykh Vladimir
f9ce96ac22 docs init 2021-03-11 19:47:11 +03:00
ChernV
93756128ef docs init 2021-03-11 18:28:30 +03:00
ChernV
377eb2a079 Update README.md 2021-03-04 13:48:23 +03:00
ChernV
6936361103 Update README.md 2021-03-04 13:35:28 +03:00
ChernV
b7b5e04498 flask logging example fix 2021-03-02 19:41:50 +03:00
ChernV
a031347f88 TgFileLogger example fix 2021-03-02 19:40:34 +03:00
ChernV
740cb1895d add toc and flask example 2021-02-09 21:47:53 +03:00
ChernV
cad9a43bf3 Update README.md 2021-02-09 19:07:30 +03:00
ChernV
985247ad1f fqa fix 2021-02-06 13:05:44 +03:00
ChernV
9119e8d952 typo fix 2021-02-06 13:03:17 +03:00
ChernV
f12b840b71 typo fix 2021-02-05 12:52:08 +03:00
ChernV
a9c73e84ed Update README.md 2021-02-05 12:50:58 +03:00
ChernV
9d6478266e LICENSE link is added 2021-02-05 11:43:20 +03:00
ChernV
7628e9f431 add start shield 2021-02-05 11:42:10 +03:00
ChernV
49a40a1620 Update README.md 2021-02-05 11:41:10 +03:00
ChernV
678640f846 license shield is added 2021-02-05 11:25:43 +03:00
ChernV
987d2cffea Merge pull request #1 from otter18/beta
v3.0 realise
2021-02-05 11:17:46 +03:00
ChernV
b9c4bd8872 Add files via upload 2021-02-05 11:04:53 +03:00
ChernV
89730a4702 Delete example_scr.jpg 2021-02-05 11:03:50 +03:00
Chernykh Vladimir
3d257f1506 v3.0 minor fix 2021-02-05 11:03:08 +03:00
Chernykh Vladimir
f9d92952b4 v3.0 initial commit 2021-02-05 10:55:57 +03:00
ChernV
361b97dad7 Delete example_scr.jpg 2021-02-05 10:02:59 +03:00
ChernV
cbe195cd34 Add files via upload 2021-02-05 10:02:40 +03:00
ChernV
c8c69b1cf9 Delete setup.cfg 2021-02-03 20:58:43 +03:00
ChernV
0d563d9203 Delete tg_logger.toml 2021-02-03 20:58:35 +03:00
Chernykh Vladimir
b455a023d9 package meta is added 2021-02-03 20:57:17 +03:00
ChernV
dd76f85e1c Delete requirements.txt 2021-02-03 20:19:45 +03:00
Chernykh Vladimir
f72e3d6ba2 v2.0.1 realise 2021-02-03 20:18:57 +03:00
Chernykh Vladimir
34e7761bcf python package architecture 2021-02-03 19:41:29 +03:00
ChernV
3c171f8cfb Update tg_logger.py 2021-01-01 16:24:50 +03:00
ChernV
3bdebb4661 Update README.md 2021-01-01 15:40:15 +03:00
ChernV
566cdaaeb4 Add files via upload 2021-01-01 15:38:33 +03:00
21 changed files with 602 additions and 155 deletions

8
.gitignore vendored Normal file
View File

@@ -0,0 +1,8 @@
__pycache__/
*.pyc
dist/
*.egg-info/
.coverage
build/
setup.cfg
tg_logger.toml

138
README.md
View File

@@ -1,40 +1,123 @@
# tg_logger tool
bridging python logging and user files to tg bot
## Example
# ![tg_logo](https://raw.githubusercontent.com/otter18/tg_logger/master/img/telegram-icon.png) Telegram logger [![GitHub Repo stars](https://img.shields.io/github/stars/otter18/tg_logger?style=social)](https://github.com/otter18/tg_logger/stargazers)
[![Pypi version](https://img.shields.io/pypi/v/tg-logger.svg)](https://pypi.org/project/tg-logger/)
[![Downloads](https://static.pepy.tech/personalized-badge/tg-logger?period=total&units=international_system&left_color=grey&right_color=orange&left_text=Downloads)](https://pepy.tech/project/tg-logger)
[![GitHub](https://img.shields.io/github/license/otter18/tg_logger)](https://github.com/otter18/tg_logger/blob/main/LICENSE)
[![Documentation Status](https://readthedocs.org/projects/tg-logger/badge/?version=latest)](https://tg-logger.readthedocs.io/en/latest/?badge=latest)
<!-- [![Pyversions](https://img.shields.io/pypi/pyversions/tg-logger.svg)](https://pypi.org/project/tg-logger/) -->
Bridging python logging and files to tg bot
Documentation is available at [Read the Docs](https://tg-logger.readthedocs.io/)
Demo is available [@tg_logger_demo_bot](https://t.me/tg_logger_demo_bot), [[repo](https://github.com/otter18/tg-logger-demo-bot)]
![intro_img](https://raw.githubusercontent.com/otter18/tg_logger/main/img/intro.jpeg)
## 🗂 Table of Contents
- [Installation & Usage](#-installation--usage)
- [Screenshot](#-screenshot)
- [Examples](#-examples)
* [Simple logging](#simple-logging)
* [Flask logging](#flask-logging)
* [Setting extra parameters to handler](#setting-extra-parameters-to-handler)
* [TgFileLogger example](#tgfilelogger-example)
- [FQA](#-fqa)
* [How to create a telegram bot?](#how-to-create-a-telegram-bot)
* [How to get **token** and **user_id**?](#how-to-get-token-and-user_id)
## 🚀 Installation & Usage
- Available by `pip install tg-logger`
- Use with `import tg_logger`
## 📱 Screenshot
![example_scr](https://raw.githubusercontent.com/otter18/tg_logger/master/img/example_scr.png)
## 📖 Examples
### Simple logging
```python
# Copyright (c) ChernV (@otter18), 2021.
import logging
import tg_logger
# Telegram data
token = "1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
users = [1111111111]
# Logging format
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s - %(message)s')
formatter = logging.Formatter('<b>%(name)s:%(levelname)s</b> - <code>%(message)s</code>')
# Setup TgLoggerHandler
tg_handler = tg_logger.TgLoggerHandler(
token=token, # tg bot token
users=users, # list of user_id
timeout=10 # default value is 10 seconds
)
tg_handler.setFormatter(formatter)
logger = logging.getLogger()
# Base logger
logger = logging.getLogger('foo')
logger.setLevel(logging.INFO)
logger.addHandler(tg_handler)
# Logging bridge setup
tg_logger.setup(logger, token=token, users=users)
# Test
logger.info("Hello from tg_logger by otter18")
```
### Flask logging
```python
from flask import Flask
import logging
import tg_logger
# Telegram data
token = "1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
users = [1111111111]
# Flask app setup
app = Flask(__name__)
app.logger.setLevel(logging.ERROR) # flask logger
tg_logger.setup(app.logger, token=token, users=users) # bridge setup
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
```
### Setting extra parameters to handler
```python
import logging
import tg_logger
# Telegram data
token = "1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
users = [1111111111]
# Base logger
logger = logging.getLogger('foo')
logger.setLevel(logging.INFO)
# Logging bridge setup
handler = tg_logger.setup(logger, token=token, users=users)
# Setting extra params
handler.setLevel(logging.DEBUG)
# Test
logger.info("Hello from tg_logger by otter18")
```
### TgFileLogger example
```python
import tg_logger
# Telegram data
token = "1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
users = [1111111111]
# TgFileLogger example
tg_files_logger = tg_logger.TgFileLogger(
token=token, # tg bot token
users=users, # list of user_id
timeout=10 # default is 10 seconds
timeout=10 # 10 seconds by default
)
file_name = "test.txt"
@@ -42,10 +125,13 @@ with open(file_name, 'w') as example_file:
example_file.write("Hello from tg_logger by otter18")
tg_files_logger.send(file_name, "Test file")
# And one more time...
logger.info("Finishing tg_logger demo")
```
## Result
![example_scr](/img/example_scr.jpg)
## 🔎 FQA
### How to create a telegram bot?
- To create bot use official [BotFather](https://t.me/BotFather) bot (descibed [here](https://core.telegram.org/bots#6-botfather))
### How to get **token** and **user_id**?
- Use [@tg_logger_demo_bot](https://t.me/tg_logger_demo_bot) with command `/id`
- Bot's **token** is shown after new bot is made
- To get **user_id** use special bots (e.g. [@userinfobot](https://t.me/userinfobot), [@JsonDumpBot](https://t.me/JsonDumpBot))

20
docs/Makefile Normal file
View File

@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

35
docs/make.bat Normal file
View File

@@ -0,0 +1,35 @@
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd

61
docs/source/conf.py Normal file
View File

@@ -0,0 +1,61 @@
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('...'))
# -- Project information -----------------------------------------------------
project = 'tg-logger'
copyright = '2021, ChernV (otter18)'
author = 'ChernV (otter18)'
# The full version, including alpha/beta/rc tags
release = 'v3.1'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ["sphinx.ext.autodoc"]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'python3'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

14
docs/source/fqa.rst Normal file
View File

@@ -0,0 +1,14 @@
FQA
====
How to create a telegram bot?
******************************
To create bot use official `BotFather <https://t.me/BotFather>`_ bot (descibed `here <https://core.telegram.org/bots#6-botfather>`_)
How to get **token** and **user_id**?
*************************************
- Use `@tg_logger_demo_bot <https://t.me/tg_logger_demo_bot>`_ with command :code:`/id`
- Bot's **token** is shown after new bot is made
- To get **user_id** use special bots (e.g. `@userinfobot <https://t.me/userinfobot>`_, `@JsonDumpBot <https://t.me/JsonDumpBot>`_)

32
docs/source/index.rst Normal file
View File

@@ -0,0 +1,32 @@
.. tg-logger documentation master file, created by
sphinx-quickstart on Thu Mar 11 18:47:28 2021.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to tg-logger's documentation!
=====================================
Demo is available `@tg_logger_demo_bot <https://t.me/tg_logger_demo_bot>`_
.. toctree::
:maxdepth: 2
:caption: Contents:
intro
modules
fqa
license
Links
=====
- Github: https://github.com/otter18/tg_logger
- Pypi: https://pypi.org/project/tg-logger
- Demo bot: https://t.me/tg_logger_demo_bot
..
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

100
docs/source/intro.rst Normal file
View File

@@ -0,0 +1,100 @@
Introduction
============
Tg-logger is took for bridging python logging and files to tg bot
Installation & Usage
********************
.. code:: bash
pip install tg-logger
.. code:: python
import tg_logger
Screenshot
**********
.. image:: https://raw.githubusercontent.com/otter18/tg_logger/master/img/example_scr.png
:alt: example screenshot
Examples
********
Simple logging
##############
.. code:: python
import logging
import tg_logger
# Telegram data
token = "1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
users = [1111111111]
# Base logger
logger = logging.getLogger('foo')
logger.setLevel(logging.INFO)
# Logging bridge setup
tg_logger.setup(logger, token=token, users=users)
# Test
logger.info("Hello from tg_logger by otter18")
Flask logging
#############
.. code:: python
from flask import Flask
import tg_logger
# Telegram data
token = "1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
users = [1111111111]
# Flask app setup
app = Flask(__name__)
app.logger.setLevel(logging.ERROR) # flask logger
tg_logger.setup(app.logger, token=token, users=users) # bridge setup
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
TgFileLogger example
####################
.. code:: python
import tg_logger
# Telegram data
token = "1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
users = [1111111111]
# TgFileLogger example
tg_files_logger = tg_logger.TgFileLogger(
token=token, # tg bot token
users=users, # list of user_id
timeout=10 # 10 seconds by default
)
file_name = "test.txt"
with open(file_name, 'w') as example_file:
example_file.write("Hello from tg_logger by otter18")
tg_files_logger.send(file_name, "Test file")

24
docs/source/license.rst Normal file
View File

@@ -0,0 +1,24 @@
License
========
MIT License
Copyright (c) 2021 ChernV
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

7
docs/source/modules.rst Normal file
View File

@@ -0,0 +1,7 @@
Module description
===================
.. automodule:: tg_logger
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,43 +1,35 @@
# Copyright (c) ChernV (@otter18), 2021.
import logging
import tg_logger
# Telegram data
token = "1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
users = [1111111111]
# Logging format
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s - %(message)s')
formatter = logging.Formatter('<b>%(name)s:%(levelname)s</b> - <code>%(message)s</code>')
# Setup TgLoggerHandler
tg_handler = tg_logger.TgLoggerHandler(
token=token, # tg bot token
users=users, # list of user_id
timeout=10 # default value is 10 seconds
)
tg_handler.setFormatter(formatter)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(tg_handler)
# Test
logger.info("Hello from tg_logger by otter18")
# TgFileLogger example
tg_files_logger = tg_logger.TgFileLogger(
token=token, # tg bot token
users=users, # list of user_id
timeout=10 # default is 10 seconds
)
file_name = "test.txt"
with open(file_name, 'w') as example_file:
example_file.write("Hello from tg_logger by otter18")
tg_files_logger.send(file_name, "Test file")
# And one more time...
logger.info("Finishing tg_logger demo")
# Copyright (c) ChernV (@otter18), 2021.
import logging
import tg_logger
# Telegram data
token = "1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
users = [1111111111]
# Base logger
logger = logging.getLogger('foo')
logger.setLevel(logging.INFO)
# Logging bridge setup
tg_logger.setup(logger, token=token, users=users)
# Test
logger.info("Hello from tg_logger by otter18")
# TgFileLogger example
tg_files_logger = tg_logger.TgFileLogger(
token=token, # tg bot token
users=users, # list of user_id
timeout=10 # default is 10 seconds
)
file_name = "test.txt"
with open(file_name, 'w') as example_file:
example_file.write("Hello from tg_logger by otter18")
tg_files_logger.send(file_name, "Test file")
# And one more time...
logger.info("Finishing tg_logger demo")

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

BIN
img/example_scr.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 KiB

BIN
img/intro.jpeg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

BIN
img/intro2.jpeg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

BIN
img/telegram-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@@ -1 +0,0 @@
pytelegrambotapi

22
setup.py Normal file
View File

@@ -0,0 +1,22 @@
from setuptools import setup, find_packages
setup(
name="tg_logger",
version="3.3",
description="A tool to bridge python logging and user files to telegram bot",
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
author="ChernV (otter18)",
author_email="vchern185@gmail.com",
url="https://github.com/otter18/tg_logger",
packages=find_packages(),
install_requires=[
"pyTelegramBotAPI>=3.7.6",
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
)

38
tg_logger/__init__.py Normal file
View File

@@ -0,0 +1,38 @@
# Copyright (c) ChernV (@otter18), 2021.
from .files import *
from .handler import *
import logging
from typing import List
def setup(base_logger: logging.Logger = logging.getLogger(),
token: str = '',
users: List[int] = [],
timeout: int = 10,
tg_format: str = '<b>%(name)s:%(levelname)s</b> - <code>%(message)s</code>'):
"""
Setup TgLogger
:param base_logger: base logging.Logger obj
:param token: tg bot token to log form
:param users: list of used_id to log to
:param timeout: seconds for retrying to send log if error occupied
:param tg_format: logging format for tg messages (html parse mode)
:return: logging.StreamHandler
"""
# Logging format
formatter = logging.Formatter(tg_format)
# Setup TgLoggerHandler
tg_handler = TgLoggerHandler(
token=token, # tg bot token
users=users, # list of user_id
timeout=timeout # default value is 10 seconds
)
tg_handler.setFormatter(formatter)
base_logger.addHandler(tg_handler)
return tg_handler

View File

@@ -1,85 +1,51 @@
# Copyright (c) ChernV (@otter18), 2021.
import logging
from logging import StreamHandler
from time import time, sleep
from typing import List
import telebot
# logging setup
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class TgLoggerHandler(StreamHandler):
"""Logger handler for tg_logger"""
def __init__(self, token: str, users: List[int], timeout: int = 10):
"""
Setup TgLoggerHandler tool
:param token: tg bot token to log form
:param users: list of used_id to log to
:param timeout: seconds for retrying to send log if error occupied
"""
super().__init__()
self.token = token
self.users = users
self.timeout = timeout
self.bot = telebot.TeleBot(token=self.token)
def emit(self, record):
msg = self.format(record)
for user_id in self.users:
t0 = time()
while time() - t0 < self.timeout:
try:
self.bot.send_message(user_id, msg)
break
except Exception as ex:
logger.exception("Exception while sending %s to %s:", msg, user_id)
sleep(1)
class TgFileLogger:
"""tg_logger tool to send files"""
def __init__(self, token: str, users: List[int], timeout: int = 10):
"""
Setup TgFileLogger tool
:param token: tg bot token to log form
:param users: list of used_id to log to
:param timeout: seconds for retrying to send log if error occupied
"""
self.token = token
self.users = users
self.timeout = timeout
self.bot = telebot.TeleBot(token=self.token)
def send(self, file_path: str, caption: str = ''):
"""
Function to send file
:param file_path: file path to log
:param caption: text to file with file
:return: None
"""
with open(file_path, 'rb') as data:
for user_id in self.users:
t0 = time()
while time() - t0 < self.timeout:
try:
self.bot.send_document(user_id, data=data, caption=caption)
logger.info("File %s successfully send to %s", file_path, user_id)
break
except Exception as ex:
logger.exception("Exception while sending %s to %s:", file_path, user_id)
sleep(1)
# Copyright (c) ChernV (@otter18), 2021.
import logging
from time import time, sleep
from typing import List
import telebot
# logging setup
logger = logging.getLogger(__name__)
class TgFileLogger:
"""tg_logger tool to send files"""
def __init__(self, token: str, users: List[int], timeout: int = 10):
"""
Setup TgFileLogger tool
:param token: tg bot token to log form
:param users: list of used_id to log to
:param timeout: seconds for retrying to send log if error occupied
"""
self.token = token
self.users = users
self.timeout = timeout
self.bot = telebot.TeleBot(token=self.token)
def send(self, file_path: str, caption: str = ''):
"""
Function to send file
:param file_path: file path to log
:param caption: text to file with file
:return: None
"""
with open(file_path, 'rb') as data:
for user_id in self.users:
t0 = time()
while time() - t0 < self.timeout:
try:
self.bot.send_document(user_id, data=data, caption=caption, parse_mode="HTML")
logger.info("File %s successfully send to %s", file_path, user_id)
break
except Exception:
logger.exception("Exception while sending %s to %s:", file_path, user_id)
sleep(1)

43
tg_logger/handler.py Normal file
View File

@@ -0,0 +1,43 @@
# Copyright (c) ChernV (@otter18), 2021.
import logging
from logging import StreamHandler
from time import time, sleep
from typing import List
import telebot
# logging setup
logger = logging.getLogger(__name__)
class TgLoggerHandler(StreamHandler):
"""Logger handler for tg_logger"""
def __init__(self, token: str, users: List[int], timeout: int = 10):
"""
Setup TgLoggerHandler class
:param token: tg bot token to log form
:param users: list of used_id to log to
:param timeout: seconds for retrying to send log if error occupied
"""
super().__init__()
self.token = token
self.users = users
self.timeout = timeout
self.bot = telebot.TeleBot(token=self.token)
def emit(self, record):
msg = self.format(record)
for user_id in self.users:
t0 = time()
while time() - t0 < self.timeout:
try:
self.bot.send_message(user_id, msg, parse_mode="HTML")
break
except Exception as ex:
logger.exception("Exception while sending %s to %s:", msg, user_id)
sleep(1)