Skip to content

Commit

Permalink
Merge pull request #2 from erayerdin/development
Browse files Browse the repository at this point in the history
v0.2.0a2
  • Loading branch information
erayerdin committed May 12, 2019
2 parents 3cc142f + 8eefcf4 commit eb21e82
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 116 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ jobs:
- pip install -r dev.requirements.txt
- pip install tgcli --upgrade
script:
- pytest --cov-config .coveragerc --cov tgcli tests/
- coveralls
- pytest --cov-config .coveragerc --cov tglogger tests/
- codecov
after_success:
- tgcli bot send -r $TELEGRAM_RECEIVER message "🍾 \`tglogger\` coverage has passed."
after_failure:
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Added
- `_TEMPLATE` to `TelegramFormatter`

### Removed
- `MESSAGE_LINE_TEMPLATE` from `tglogger.formatter`

## [v0.1.0a1] - 2019-05-12
### Added
- `TelegramHandler`
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ Telegram chat via a bot.

| | Build | Coverage |
|--------------|-------|----------|
| **Master** | [![Travis (.com) master](https://img.shields.io/travis/com/erayerdin/tglogger/master.svg?style=flat-square&logo=travis&logoColor=white)][travis_url] | [![](https://img.shields.io/coveralls/github/erayerdin/tglogger/master.svg?logo=star&logoColor=white&style=flat-square)][coveralls_url] |
| **Development** | [![Travis (.com) development](https://img.shields.io/travis/com/erayerdin/tglogger/development.svg?style=flat-square&logo=travis&logoColor=white)][travis_url] | [![](https://img.shields.io/coveralls/github/erayerdin/tglogger/development.svg?logo=star&logoColor=white&style=flat-square)][coveralls_url] |
| **Master** | [![Travis (.com) master](https://img.shields.io/travis/com/erayerdin/tglogger/master.svg?style=flat-square&logo=travis&logoColor=white)][travis_url] | [![Codecov (master)](https://img.shields.io/codecov/c/github/erayerdin/tglogger/master.svg?style=flat-square)][covecov_url] |
| **Development** | [![Travis (.com) development](https://img.shields.io/travis/com/erayerdin/tglogger/development.svg?style=flat-square&logo=travis&logoColor=white)][travis_url] | [![Codecov (development)](https://img.shields.io/codecov/c/github/erayerdin/tglogger/master.svg?style=flat-square)][covecov_url] |

[travis_url]: https://travis-ci.com/erayerdin/tglogger
[coveralls_url]: https://coveralls.io/github/erayerdin/tglogger
[covecov_url]: https://codecov.io/gh/erayerdin/tglogger

## Installing

Expand Down
2 changes: 1 addition & 1 deletion dev.requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pytest==4.4.2
pytest-cov==2.7.1
requests_mock==1.6.0
coveralls==1.7.0
codecov==2.0.15
mkdocs==1.0.4
mkdocs-material==4.2.0
4 changes: 4 additions & 0 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ logger.error("foo")

![Screenshot](img/message_example.jpeg)

!!! tip
You can set `TELEGRAM_BOT_TOKEN` and `TELEGRAM_RECEIVER` environment
variables instead of setting `bot_token` and `receiver`.

[^1]:
You can change level offset by passing `level` to `TelegramHandler`
while you initialize it.
50 changes: 0 additions & 50 deletions tests/test_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,56 +5,6 @@
from tglogger import formatter


class TestMessageLineTemplate:
def test_is_list_or_tuple(self):
assert isinstance(
formatter.MESSAGE_LINE_TEMPLATES, list
) or isinstance(formatter.MESSAGE_LINE_TEMPLATES, tuple)

def test_item_banner_hashtag(self):
assert "#tglogger" in formatter.MESSAGE_LINE_TEMPLATES

def test_item_logger_name(self):
assert (
"*Logger Name:* {logger_name}" in formatter.MESSAGE_LINE_TEMPLATES
)

def test_item_system_date(self):
assert (
"*System Date:* {system_date}" in formatter.MESSAGE_LINE_TEMPLATES
)

def test_item_level(self):
assert "*Level:* #{level_name}" in formatter.MESSAGE_LINE_TEMPLATES

def test_item_path_and_line(self):
assert (
"*Path and Line:* _{path}_:{lineno}"
in formatter.MESSAGE_LINE_TEMPLATES
)

def test_item_function_or_method(self):
assert (
"*Function/Method:* _{func_name}_"
in formatter.MESSAGE_LINE_TEMPLATES
)

def test_item_thread(self):
assert (
"*Thread ID and Name:* \[{thread_id}] {thread_name}"
in formatter.MESSAGE_LINE_TEMPLATES
)

def test_item_process(self):
assert (
"*Process ID and Name:* \[{process_id}] {process_name}"
in formatter.MESSAGE_LINE_TEMPLATES
)

def test_item_message(self):
assert "\n*Message*\n{message}\n" in formatter.MESSAGE_LINE_TEMPLATES


class TestReformatMarkdownSafe:
def test_replace_underscore(self):
example = "foo_bar_baz"
Expand Down
88 changes: 32 additions & 56 deletions tglogger/formatter.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,7 @@
# todo - 2 class doc

import logging

MESSAGE_LINE_TEMPLATES = (
"#tglogger",
"*Logger Name:* {logger_name}",
"*System Date:* {system_date}",
"*Level:* #{level_name}",
"*Path and Line:* _{path}_:{lineno}",
"*Function/Method:* _{func_name}_",
"*Thread ID and Name:* \[{thread_id}] {thread_name}",
"*Process ID and Name:* \[{process_id}] {process_name}",
"\n*Message*\n{message}\n",
)
from textwrap import dedent


def reformat_markdown_safe(text: str) -> str:
Expand All @@ -25,63 +14,50 @@ def reformat_markdown_safe(text: str) -> str:

class TelegramFormatter(logging.Formatter):
# todo 3 - class doc
_TEMPLATE = dedent(
"""
#tglogger
*Logger Name:* {logger_name}
*System Date:* {system_date}
*Level:* #{level_name}
*Path and Line:* _{path}_:{lineno}
*Function/Method:* _{func_name}_
*Thread ID and Name:* \[{thread_id}] {thread_name}
*Process ID and Name:* \[{process_id}] {process_name}
*Message*
{message}
"""
)

def format(self, record: logging.LogRecord):
message_lines = [MESSAGE_LINE_TEMPLATES[0]]
data = dict()

logger_name = record.name
message_lines.append(
MESSAGE_LINE_TEMPLATES[1].format(logger_name=logger_name)
)
data["logger_name"] = record.name

try:
from django import timezone as datetime
from django import settings

tz = getattr(settings, "TIME_ZONE", "No Timezone")

system_date = "{now} ({zone})".format(now=datetime.now(), zone=tz)
data["system_date"] = "{now} ({zone})".format(
now=datetime.now(), zone=tz
)
except ImportError:
from datetime import datetime

system_date = datetime.now()
message_lines.append(
MESSAGE_LINE_TEMPLATES[2].format(system_date=system_date)
)

level_name = record.levelname.lower()
message_lines.append(
MESSAGE_LINE_TEMPLATES[3].format(level_name=level_name)
)

path = reformat_markdown_safe(record.pathname)
lineno = record.lineno
message_lines.append(
MESSAGE_LINE_TEMPLATES[4].format(path=path, lineno=lineno)
)

func_name = reformat_markdown_safe(record.funcName)
message_lines.append(
MESSAGE_LINE_TEMPLATES[5].format(func_name=func_name)
)

thread_id = record.thread
thread_name = record.threadName
message_lines.append(
MESSAGE_LINE_TEMPLATES[6].format(
thread_id=thread_id, thread_name=thread_name
)
)
data["system_date"] = datetime.now()

process_id = record.process
process_name = record.processName
message_lines.append(
MESSAGE_LINE_TEMPLATES[7].format(
process_id=process_id, process_name=process_name
)
)
data["level_name"] = record.levelname.lower()
data["path"] = reformat_markdown_safe(record.pathname)
data["lineno"] = record.lineno
data["func_name"] = reformat_markdown_safe(record.funcName)
data["thread_id"] = record.thread
data["thread_name"] = record.threadName

message = record.getMessage()
message_lines.append(MESSAGE_LINE_TEMPLATES[8].format(message=message))
data["process_id"] = record.process
data["process_name"] = record.processName
data["message"] = record.getMessage()

return "\n".join(message_lines)
return self._TEMPLATE.format_map(data)
8 changes: 4 additions & 4 deletions tglogger/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ def __init__(
bot_token: str = os.environ["TELEGRAM_BOT_TOKEN"],
receiver: str = os.environ["TELEGRAM_RECEIVER"],
):
self.__bot_token = bot_token
self.__receiver = receiver
self._bot_token = bot_token
self._receiver = receiver
super().__init__(level)

def emit(self, record):
session = request.BotSession(token=self.__bot_token)
session = request.BotSession(token=self._bot_token)
req = request.SendMessageRequest(
session, self.__receiver, self.format(record)
session, self._receiver, self.format(record)
)
return session.send(req)

0 comments on commit eb21e82

Please sign in to comment.