Skip to content

Commit

Permalink
Enables logging to a file (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
hiwakaba authored Oct 11, 2024
1 parent 2a709a1 commit 7d8e2bc
Show file tree
Hide file tree
Showing 5 changed files with 173 additions and 26 deletions.
5 changes: 5 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
History
=======

1.1.2 (2024-10-11)
-------------------

* Enables logging to a file

1.1.1 (2024-10-09)
-------------------

Expand Down
51 changes: 51 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,57 @@ Let's try to get a token and create a resource.::
... )
>>> myresource.resp.body // {"result":true...


Settings
---------

To customize the settings of this library, place the configuration file in one of the following locations.::

$PWD/k2hr3client.ini
$HOME/.k2hr3client.ini
/etc/antpickax/k2hr3client.ini

To use the settings in your program, see the following example.::

>>> from k2hr3client import CONFIG
>>> print(CONFIG['DEFAULT']['iaas_user'])
demo

Here are the default settings.

+---------+------------------------+-------------------------------------------------+------------------------+
| section | key name | description | default value |
+=========+========================+=================================================+========================+
| DEFAULT | debug | Enable debug log if True | False |
+---------+------------------------+-------------------------------------------------+------------------------+
| DEFAULT | iaas_url | IaaS API URL(OpenStack) | http://172.24.4.1 |
+---------+------------------------+-------------------------------------------------+------------------------+
| DEFAULT | iaas_project | IaaS project name | demo |
+---------+------------------------+-------------------------------------------------+------------------------+
| DEFAULT | iaas_user | IaaS user name | demo |
+---------+------------------------+-------------------------------------------------+------------------------+
| DEFAULT | iaas_password | IaaS password of the user | password |
+---------+------------------------+-------------------------------------------------+------------------------+
| DEFAULT | log_file | log file name | sys.stderr |
+---------+------------------------+-------------------------------------------------+------------------------+
| DEFAULT | log_dir | log directory name | logs |
+---------+------------------------+-------------------------------------------------+------------------------+
| DEFAULT | log_level | log level(error,warn,info,debug,notset) | info |
+---------+------------------------+-------------------------------------------------+------------------------+
| k2hr3 | api_url | k2hr3 API URL | http://127.0.0.1:18080 |
+---------+------------------------+-------------------------------------------------+------------------------+
| k2hr3 | api_version | k2hr3 api version | v1 |
+---------+------------------------+-------------------------------------------------+------------------------+
| http | timeout_seconds | timeout to establish tcp connections | 30 |
+---------+------------------------+-------------------------------------------------+------------------------+
| http | retry_interval_seconds | interval to reconnect with HTTP server | 60 |
+---------+------------------------+-------------------------------------------------+------------------------+
| http | max_retries | maximum count to reconnect with HTTP server | 3 |
+---------+------------------------+-------------------------------------------------+------------------------+
| http | allow_self_signed_cert | Allow to use self-signed certification in HTTPS | False |
+---------+------------------------+-------------------------------------------------+------------------------+


Development
------------

Expand Down
41 changes: 35 additions & 6 deletions conf/k2hr3client.ini
Original file line number Diff line number Diff line change
@@ -1,19 +1,48 @@
# -*- coding: utf-8 -*-
#
# k2hr3client - Python client for K2HR3 REST API
#
# Copyright 2024 LY Corporation
#
# K2HR3 is K2hdkc based Resource and Roles and policy Rules, gathers
# common management information for the cloud.
# K2HR3 can dynamically manage information as "who", "what", "operate".
# These are stored as roles, resources, policies in K2hdkc, and the
# client system can dynamically read and modify these information.
#
# For the full copyright and license information, please view
# the license file that was distributed with this source code.
#
# AUTHOR: Hirotaka Wakabayashi
# CREATE: Fri Oct 11 2024
# REVISION:
#
#
[DEFAULT]
debug = False
iaas_url = "http://172.24.4.1"
iaas_project = "demo"
iaas_user = "demo"
iaas_password = "password"
iaas_url = http://172.24.4.1
iaas_project = demo
iaas_user = demo
iaas_password = password
log_file = sys.stdout
log_dir = logs
log_level = logging.INFO

[k2hr3]
api_url = "http://127.0.0.1:18080"
api_version = "v1"
api_url = http://127.0.0.1:18080
api_version = v1

[http]
timeout_seconds = 30
retry_interval_seconds = 60
max_retries = 3
allow_self_signed_cert = True

#
# Local variables:
# tab-width: 4
# c-basic-offset: 4
# End:
# vim600: expandtab sw=4 ts=4 fdm=marker
# vim<600: expandtab sw=4 ts=4
#
44 changes: 26 additions & 18 deletions docs/locale/ja/LC_MESSAGES/history.po
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ msgid ""
msgstr ""
"Project-Id-Version: k2hr3client \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-10-09 15:10+0900\n"
"POT-Creation-Date: 2024-10-11 16:22+0900\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language: ja\n"
Expand All @@ -26,74 +26,82 @@ msgid "History"
msgstr "歴史"

#: ../../../HISTORY.rst:6
msgid "1.1.1 (2024-10-09)"
msgid "1.1.2 (2024-10-11)"
msgstr ""

#: ../../../HISTORY.rst:8
msgid "Enables logging to a file"
msgstr "ログファイルへのログ出力をサポート"

#: ../../../HISTORY.rst:10
msgid "1.1.1 (2024-10-09)"
msgstr ""

#: ../../../HISTORY.rst:13
msgid "Removes hardcodings"
msgstr "ハードコーディングを削除"

#: ../../../HISTORY.rst:9
#: ../../../HISTORY.rst:14
msgid "Adds Configuration Interface"
msgstr "設定用インターフェースを追加"

#: ../../../HISTORY.rst:10 ../../../HISTORY.rst:17
#: ../../../HISTORY.rst:15 ../../../HISTORY.rst:22
msgid "Updates the docs"
msgstr "ドキュメントの更新"

#: ../../../HISTORY.rst:13
#: ../../../HISTORY.rst:18
msgid "1.1.0 (2024-10-04)"
msgstr ""

#: ../../../HISTORY.rst:15
#: ../../../HISTORY.rst:20
msgid "Removes the deprecated Interfaces"
msgstr "非推奨のインタフェースを削除"

#: ../../../HISTORY.rst:16
#: ../../../HISTORY.rst:21
msgid "Removes the examples"
msgstr "例示プログラムの削除"

#: ../../../HISTORY.rst:20
#: ../../../HISTORY.rst:25
msgid "1.0.3 (2024-10-03)"
msgstr ""

#: ../../../HISTORY.rst:22
#: ../../../HISTORY.rst:27
msgid "Fixes the K2hr3 API version"
msgstr "K2hr3 APIのバージョンを固定化"

#: ../../../HISTORY.rst:23
#: ../../../HISTORY.rst:28
msgid "Deprecates K2hr3Resource.create_conf_resource params"
msgstr "K2hr3Resource.create_conf_resourceのパラメータを一部非推奨化"

#: ../../../HISTORY.rst:26
#: ../../../HISTORY.rst:31
msgid "1.0.2 (2024-09-26)"
msgstr ""

#: ../../../HISTORY.rst:28
#: ../../../HISTORY.rst:33
msgid "Fixes lint errors"
msgstr "静的解析ツールのエラーを修正"

#: ../../../HISTORY.rst:31
#: ../../../HISTORY.rst:36
msgid "1.0.1 (2024-09-25)"
msgstr ""

#: ../../../HISTORY.rst:33
#: ../../../HISTORY.rst:38
msgid "Fixes resource API bugs"
msgstr "Resource APIの不具合を修正"

#: ../../../HISTORY.rst:36
#: ../../../HISTORY.rst:41
msgid "1.0.0 (2024-08-28)"
msgstr ""

#: ../../../HISTORY.rst:38
#: ../../../HISTORY.rst:43
msgid "Supports the other APIs"
msgstr "他のAPIをサポート"

#: ../../../HISTORY.rst:41
#: ../../../HISTORY.rst:46
msgid "0.0.1 (2020-08-28)"
msgstr ""

#: ../../../HISTORY.rst:43
#: ../../../HISTORY.rst:48
msgid "Supports Token, Resource, Policy and Role API"
msgstr "トークン、リソース、ポリシーおよびロールAPIをサポート"

58 changes: 56 additions & 2 deletions src/k2hr3client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,17 @@
"""K2HR3 Python Client of Token API."""

__author__ = 'Hirotaka Wakabayashi <[email protected]>'
__version__ = '1.1.1'
__version__ = '1.1.2'

import configparser
import logging
from logging.handlers import TimedRotatingFileHandler
from logging import StreamHandler
from pathlib import Path
import sys

LOG = logging.getLogger(__name__)

if sys.platform.startswith('win'):
raise ImportError(r'Currently we do not test well on windows')

Expand Down Expand Up @@ -61,7 +66,7 @@ def get_version() -> str:
default_section['iaas_password'] = "password"
default_section['log_file'] = "sys.stderr"
default_section['log_dir'] = "logs"
default_section['log_level'] = "logging.INFO"
default_section['log_level'] = "info"

# [k2hr3]
# api_url = "http://127.0.0.1:18080"
Expand Down Expand Up @@ -100,6 +105,55 @@ def get_version() -> str:
CONFIG.read(my_config.absolute())
break

# 3. Configure logger
# 3.1. loglevel
_nametolevel = {
'error': logging.ERROR,
'warn': logging.WARNING,
'info': logging.INFO,
'debug': logging.DEBUG,
'notset': logging.NOTSET
}
LOG_LEVEL = logging.INFO # noqa
if CONFIG['DEFAULT'].get('log_level'):
LOG_LEVEL = _nametolevel.get(
CONFIG['DEFAULT'].get('log_level'),
logging.INFO)
LOG.setLevel(LOG_LEVEL)

# 3.2. format
formatter = logging.Formatter(
'%(asctime)-15s %(levelname)s %(name)s:%(lineno)d %(message)s')
# 3.3. handler
# Add the log message handler to the logger
if CONFIG['DEFAULT'].get('log_file') == 'sys.stdout':
stream_handler = StreamHandler(sys.stdout)
LOG.addHandler(stream_handler)
stream_handler.setFormatter(formatter)
elif CONFIG['DEFAULT'].get('log_file') == 'sys.stderr':
stream_handler = StreamHandler(sys.stderr) # default
LOG.addHandler(stream_handler)
stream_handler.setFormatter(formatter)

# log_dir
log_dir_path = Path('.') # default
log_dir = CONFIG['DEFAULT'].get('log_dir')
if log_dir:
log_dir_path = Path(log_dir)
log_dir_path.mkdir(parents=True, exist_ok=True)

# log_file
log_file = CONFIG['DEFAULT'].get('log_file')
if log_file:
log_file_path = log_dir_path.joinpath(log_file)
log_file_path.touch()
handler = TimedRotatingFileHandler(
log_file_path.absolute(),
when='midnight', encoding='UTF-8',
backupCount=31)
handler.setFormatter(formatter)
LOG.addHandler(handler)

#
# Local variables:
# tab-width: 4
Expand Down

0 comments on commit 7d8e2bc

Please sign in to comment.