Skip to content

Commit d99e96c

Browse files
committed
Added logger, config auto initialize with default file 🍩 🍪
1 parent 6032547 commit d99e96c

61 files changed

Lines changed: 281 additions & 98 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.gitignore

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
# Files
22
*.pyc
3-
bootstrap.min.css
4-
.coverage
53
*.db
4+
*.log
5+
.coverage
6+
bootstrap.min.css
67

78
# Directory
89
*.egg-info/

README.md

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<p align="center"><img src="qolugo/static/logo/logov2.png" alt="pygmy" height="200px"></p>
1+
<p align="center"><img src="pygmyui/static/logo/logov2.png" alt="pygmy" height="200px"></p>
22

33
Pygmy
44
=====
@@ -55,7 +55,7 @@ Technical Info
5555

5656
- Python 3, Javascript, JQuery, HTML, CSS
5757
- REST API: Flask
58-
- Qolugo: Django(It serves the web user interface)
58+
- Pygmyui: Django(It serves the web user interface)
5959
- DB: PostgreSQL/MySQL/SQLite
6060
- Others: SQLAlchmey, JWT
6161

@@ -78,11 +78,11 @@ Note:
7878

7979
1. The project has two config files:
8080
- pygmy.cfg: `pygmy/config/pygmy.cfg` rest API and pygmy core settings file
81-
- settings.py: `qolugo/qolugo/settings.py` Django settings file
81+
- settings.py: `pygmyui/pygmyui/settings.py` Django settings file
8282
2. SQLite is default db, if you are using PostgreSQL or MySQL with this project, make sure they are installed into the system.
8383
3. To modify config settings vim `pygmy/config/pygmy.cfg`
8484
4. You can run pygmy shell present in src directory to run the program on terminal. `python shell`
85-
5. By default in `qolugo/qolugo/settings.py` DEBUG is set to True, set it to False in production
85+
5. By default in `pygmyui/pygmyui/settings.py` DEBUG is set to True, set it to False in production
8686

8787
DB Setup:
8888
=========
@@ -258,6 +258,26 @@ I would like to thank DigitalOcean for providing initial hosting to Pygmy projec
258258
License
259259
=======
260260

261-
The MIT license (MIT)
261+
MIT License
262+
263+
Copyright (c) 2017 Amit Tripathi(https://twitter.com/amitt019)
264+
265+
Permission is hereby granted, free of charge, to any person obtaining a copy
266+
of this software and associated documentation files (the "Software"), to deal
267+
in the Software without restriction, including without limitation the rights
268+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
269+
copies of the Software, and to permit persons to whom the Software is
270+
furnished to do so, subject to the following conditions:
271+
272+
The above copyright notice and this permission notice shall be included in all
273+
copies or substantial portions of the Software.
274+
275+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
276+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
277+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
278+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
279+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
280+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
281+
SOFTWARE.
262282

263283
[Read License Terms](https://github.com/amitt001/pygmy/blob/master/LICENSE)

init.d/pyui

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
#!/bin/bash
2-
# init.d script for qolugo app
2+
# init.d script for pygmyui app
33

4-
NAME=qolugo
4+
NAME=pygmyui
55
PIDFILE=/var/run/$NAME.pid
66

77
PORT=8000
8-
APP_DIR=/opt/pygyco/qolugo
8+
APP_DIR=/opt/pygyco/pygmyui
99
PYTHONPATH='/opt/pygyco/env/bin/gunicorn'
10-
APP_ARGS='--log-file /var/log/pygmy/uierror_logs.log --access-logfile /var/log/pygmy/uiacclogs.log --bind 127.0.0.1:8000 --workers 2 qolugo.wsgi'
10+
APP_ARGS='--log-file /var/log/pygmy/uierror_logs.log --access-logfile /var/log/pygmy/uiacclogs.log --bind 127.0.0.1:8000 --workers 2 pygmyui.wsgi'
1111
APP_STOP_ARGS='--stop $PIDFILE'
1212
APP_RELOAD_ARGS='--reload $PIDFILE'
1313

pygmy/config/config.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,21 @@ class Configuration:
99
def __init__(self):
1010
# default sqlite3
1111
# TODO: Take this from cfg files
12+
self.default_config_path = 'pygmy/config/pygmy.cfg'
1213
self.cfg = None
1314
self.debug = False
1415
self.schema = None
1516
self.host = None
1617
self.port = None
1718
self.secret = None
19+
self.logging = None
1820
self.webservice_url = None
1921
self.database = None
22+
self.initialize()
2023

2124
def _read_cfg(self):
2225
self.cfg = ConfigParser()
23-
self.cfg.read(os.environ[_CONFIG_ENV_VAR])
26+
self.cfg.read(os.environ.get(_CONFIG_ENV_VAR, self.default_config_path))
2427

2528
def __getattr__(self, name):
2629
"""Add sections dynamically. With this no need to define
@@ -46,6 +49,7 @@ def initialize(self):
4649
self.host = self.cfg['pygmy']['host']
4750
self.port = self.cfg['pygmy']['port']
4851
self.secret = self.cfg['pygmy']['flask_secret']
52+
self.logging = self.cfg['logging']
4953
self.webservice_url = "{0}://{1}:{2}".format(
5054
self.schema, self.host, self.port)
5155

pygmy/config/pygmy.cfg

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,8 @@ jwt_token_blacklist_engine = None
3232

3333
[pygmy_internal]
3434
pygmy_header_key = KJ*57*6)(*&^dh
35+
36+
[logging]
37+
filepath = pygmy/data/pygmy.log
38+
level = DEBUG
39+
format = %%(asctime)s - %%(name)s - %%(levelname)s - %%(message)s

pygmy/config/pygmy_test.cfg

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,9 @@ jwt_token_blacklist_engine = None
3333

3434
[pygmy_internal]
3535
pygmy_header_key = KJ*57*6)(*&^dh
36+
37+
38+
[logging]
39+
filepath = pygmy/data/pygmy_test.log
40+
level = DEBUG
41+
format = %%(asctime)s - %%(name)s - %%(levelname)s - %%(message)s

pygmy/core/hashdigest.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,3 @@ def unshorten(self, s):
6969
for i in range(1000):
7070
sh = hd.shorten(1099)
7171
hd.decode(sh)
72-
print(time.time() - t)

pygmy/core/logger.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import logging
2+
import threading
3+
4+
from pygmy.config import config
5+
6+
7+
class Logger:
8+
"""Configure singleton logger for application and return its instance."""
9+
_lock = threading.Lock()
10+
_instance = None
11+
12+
def __new__(cls, filename=None, level=logging.DEBUG, format=None):
13+
log_config = {'level': getattr(logging, level, logging.DEBUG)}
14+
if filename:
15+
log_config.update({'filename': filename})
16+
if format:
17+
log_config.update({'format': format})
18+
19+
with cls._lock:
20+
if cls._instance is None:
21+
logging.basicConfig(**log_config)
22+
logger = logging.getLogger(__name__)
23+
cls._instance = logger
24+
cls._instance.info('Logger created for {}'.format(__name__))
25+
cls._add_stream_handler(level, format)
26+
27+
cls._instance.info('Logging setup done for {}'.format(__name__))
28+
return cls._instance
29+
30+
@classmethod
31+
def _add_stream_handler(cls, level, format):
32+
cls._instance.info('Adding stream handler to logger')
33+
handler = logging.StreamHandler()
34+
handler.setLevel(level)
35+
if format:
36+
formatter = logging.Formatter(format)
37+
handler.setFormatter(formatter)
38+
cls._instance.addHandler(handler)
39+
40+
41+
log = Logger(config.logging['filepath'], config.logging['level'], config.logging['format'])

pygmy/database/base.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from sqlalchemy.ext.declarative import declarative_base
44

55
from pygmy.config import config
6+
from pygmy.core.logger import log
67

78

89
class BaseDatabase:
@@ -25,7 +26,7 @@ def abort(self):
2526

2627
def initialize(self, debug=False):
2728
self.url = config.database['url']
28-
print(self.url)
29+
log.info('DB URL: {}'.format(self.url))
2930
self._prepare(self.url)
3031
self.engine = create_engine(self.url, echo=debug)
3132
session = sessionmaker(bind=self.engine)

pygmy/model/link.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ def add(self, db, long_url, **kwargs):
177177
try:
178178
db.commit()
179179
except IntegrityError:
180+
db.rollback()
180181
raise ShortURLUnavailable('Short URL already taken or unavailable')
181182
return self.link
182183

0 commit comments

Comments
 (0)