Skip to content

Commit 6ac550f

Browse files
authored
add `Django Logging' recipe. (#187)
1 parent 00f47e1 commit 6ac550f

File tree

9 files changed

+267
-9
lines changed

9 files changed

+267
-9
lines changed

Pipfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ flake8-django = "*"
2222
django-types = "*"
2323
types-psycopg2 = "*"
2424
types-redis = "*"
25+
colorlog = "*"
2526

2627
[requires]
2728
python_version = "3.9"

Pipfile.lock

Lines changed: 10 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@
170170
- [Django - Quick Start](https://leven-cn.github.io/python-cookbook/recipes/web/django_quickstart)
171171
- [Django DB - PostgreSQL](https://leven-cn.github.io/python-cookbook/recipes/web/django_db_postgresql)
172172
- [Django Cache - Redis](https://leven-cn.github.io/python-cookbook/recipes/web/django_cache_redis)
173+
- [Django Logging](https://leven-cn.github.io/python-cookbook/recipes/web/django_logging)
173174
- PostgreSQL
174175
- [PostgreSQL - Setup](https://leven-cn.github.io/python-cookbook/recipes/web/postgresql_setup)
175176
- [PostgreSQL CLI - Usage](https://leven-cn.github.io/python-cookbook/recipes/web/postgresql_usage)

django_project/django_project/settings.py

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,8 @@
135135

136136

137137
# Cache
138-
# https://docs.djangoproject.com/en/3.2/ref/settings/#caches
138+
# https://docs.djangoproject.com/en/4.1/ref/settings/#caches
139+
# https://docs.djangoproject.com/en/4.1/topics/cache/
139140

140141
CACHES = {
141142
'default': {
@@ -177,3 +178,96 @@
177178
},
178179
},
179180
}
181+
182+
183+
# Logging
184+
# https://docs.djangoproject.com/en/4.1/topics/logging/
185+
186+
LOGGING = {
187+
'version': 1,
188+
'disable_existing_loggers': True,
189+
'formatters': {
190+
'debug': {
191+
'format': '[%(levelname)s] [%(asctime)s] [%(filename)s:%(lineno)d] %(message)s',
192+
},
193+
'info': {
194+
'format': '[%(levelname)s] [%(asctime)s] %(message)s',
195+
},
196+
'color_debug': {
197+
'format': '%(log_color)s[%(asctime)s] [%(filename)s:%(lineno)d] %(message)s',
198+
'class': 'colorlog.ColoredFormatter',
199+
'log_colors': {
200+
'DEBUG': 'cyan white',
201+
'INFO': 'green',
202+
'WARNING': 'yellow',
203+
'ERROR': 'red',
204+
'CRITICAL': 'bold_red',
205+
},
206+
},
207+
'color': {
208+
'format': '%(log_color)s[%(asctime)s] %(message)s',
209+
'class': 'colorlog.ColoredFormatter',
210+
'log_colors': {
211+
'DEBUG': 'cyan white',
212+
'INFO': 'green',
213+
'WARNING': 'yellow',
214+
'ERROR': 'red',
215+
'CRITICAL': 'bold_red',
216+
},
217+
},
218+
'standard': {
219+
'format': '[%(levelname)s] [%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
220+
'[%(message)s]'
221+
},
222+
'collect': {
223+
'format': '%(message)s',
224+
},
225+
},
226+
'filters': {
227+
'require_debug_true': {
228+
'()': 'django.utils.log.RequireDebugTrue',
229+
},
230+
'require_debug_false': {
231+
'()': 'django.utils.log.RequireDebugFalse',
232+
},
233+
},
234+
'handlers': {
235+
'console': {
236+
'level': 'INFO',
237+
'filters': ['require_debug_false'],
238+
'class': 'logging.StreamHandler',
239+
'formatter': 'color',
240+
},
241+
'console_debug': {
242+
'level': 'DEBUG',
243+
'filters': ['require_debug_true'],
244+
'class': 'logging.StreamHandler',
245+
'formatter': 'color_debug',
246+
},
247+
},
248+
'loggers': {
249+
'django': {
250+
'handlers': ['console'],
251+
'propagate': True,
252+
},
253+
'django.request': {
254+
'handlers': ['console'],
255+
'level': 'ERROR',
256+
'propagate': False,
257+
},
258+
'': {
259+
'handlers': ['console_debug'],
260+
'level': 'DEBUG',
261+
},
262+
'requests': {
263+
'handlers': ['console'],
264+
'level': 'INFO',
265+
'propagate': False,
266+
},
267+
'elasticsearch': {
268+
'handlers': ['console'],
269+
'level': 'INFO',
270+
'propagate': False,
271+
},
272+
},
273+
}

django_project/example_app/views.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
from collections import OrderedDict
23

34
from django.core.cache import cache
@@ -8,6 +9,8 @@
89
CACHE_KEY = 'example'
910
CACHE_TIMEOUT = 10
1011

12+
logger = logging.getLogger()
13+
1114

1215
def index(request: HttpRequest) -> HttpResponse:
1316
return HttpResponse('Hello, world.')
@@ -39,15 +42,19 @@ def use_cache(request: HttpRequest) -> HttpResponse:
3942
assert cache.get(CACHE_KEY) == {'a': 1, 'b': 2, 'c': None}
4043

4144
# default value
45+
default_value = 'default value'
4246
assert cache.get('non-exists-key') is None
43-
assert cache.get('non-exists-key', 'default value') == 'default value'
47+
logger.warning('non-exists-key')
48+
assert cache.get('non-exists-key', default_value) == default_value
49+
logger.debug(f'cache get: {default_value}')
4450

4551
# get_or_set
4652
assert cache.get_or_set(CACHE_KEY, 2, CACHE_TIMEOUT) == {'a': 1, 'b': 2, 'c': None}
4753
assert cache.get_or_set('non-exists-key', 2, CACHE_TIMEOUT) == 2
4854

4955
# delete
5056
cache.delete(CACHE_KEY)
57+
logger.error('cache deleted')
5158

5259
cache.set('num', 1)
5360
assert cache.incr('num') == 2
@@ -60,4 +67,6 @@ def use_cache(request: HttpRequest) -> HttpResponse:
6067
assert cache.get_many(['a', 'b', 'c']) == OrderedDict({'a': 1, 'b': 2, 'c': None})
6168
cache.delete_many(['a', 'b', 'c'])
6269

70+
logger.info('finished')
71+
6372
return HttpResponse('ok')

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ test = [
4343
"flake8-django",
4444
"django-types",
4545
"types-redis",
46+
"colorlog",
4647
]
4748
doc = [
4849
]

recipes/core/python_project.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
```bash
66
pipenv --python 3.9
77

8-
pipenv install --dev black isort mypy 'flake8>=4.0' pyupgrade 'pytest>=7.1' 'coverage>=6.4' 'pytest-cov>=3.0' flake8-django 'django-stubs[compatible-mypy]>=1.12' types-redis
8+
pipenv install --dev black isort mypy 'flake8>=4.0' pyupgrade 'pytest>=7.1' 'coverage>=6.4' 'pytest-cov>=3.0' \
9+
flake8-django 'django-stubs[compatible-mypy]>=1.12' types-redis
910
```
1011

1112
## `pyproject.toml`
@@ -41,7 +42,6 @@ dependencies = [
4142
"django ~= 3.2",
4243
"psycopg2 >= 2.8",
4344
"redis >= 4.0",
44-
"django-redis",
4545

4646
"requests >=2.6",
4747
"configparser; python_version == '2.7'",

recipes/web/django_cache_redis.md

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
## Dependencies
44

5-
- PostgreSQL *11+*.
6-
See [PostgreSQL - Setup](https://leven-cn.github.io/python-cookbook/recipes/web/postgresql_setup)
7-
and [PostgreSQL CLI - Usage](https://leven-cn.github.io/python-cookbook/recipes/web/postgresql_usage).
5+
- Redis *5.0+*.
6+
See [Redis - Setup](https://leven-cn.github.io/python-cookbook/recipes/web/redis_setup)
7+
and [Redis CLI - Basic Usage](https://leven-cn.github.io/python-cookbook/recipes/web/redis_usage_basic).
88

99
```toml
1010
# pyproject.toml
@@ -36,6 +36,7 @@ pipenv install django-redis
3636

3737
# Cache
3838
# https://docs.djangoproject.com/en/4.1/ref/settings/#caches
39+
# https://docs.djangoproject.com/en/4.1/topics/cache/
3940

4041
CACHES = {
4142
'default': {
@@ -46,11 +47,14 @@ CACHES = {
4647

4748
### Django 4.0+
4849

50+
#### Standalone Mode
51+
4952
```python
5053
# settings.py
5154

5255
# Cache
5356
# https://docs.djangoproject.com/en/4.1/ref/settings/#caches
57+
# https://docs.djangoproject.com/en/4.1/topics/cache/
5458
#
5559
# LOCATION:
5660
# - redis://localhost:6379/0
@@ -80,11 +84,14 @@ CACHES = {
8084
}
8185
```
8286

87+
#### Replication Mode
88+
8389
```python
8490
# settings.py
8591

8692
# Cache
8793
# https://docs.djangoproject.com/en/4.1/ref/settings/#caches
94+
# https://docs.djangoproject.com/en/4.1/topics/cache/
8895
#
8996
# LOCATION:
9097
# - redis://localhost:6379/0
@@ -125,6 +132,7 @@ CACHES = {
125132

126133
# Cache
127134
# https://docs.djangoproject.com/en/3.2/ref/settings/#caches
135+
# https://docs.djangoproject.com/en/3.2/topics/cache/
128136

129137
CACHES = {
130138
'default': {

0 commit comments

Comments
 (0)