├── .gitignore ├── .pylint.cfg ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── django_logutils ├── __init__.py ├── conf.py ├── middleware.py ├── models.py ├── static │ ├── css │ │ └── django_logutils.css │ ├── img │ │ └── .gitignore │ └── js │ │ └── django_logutils.js ├── templates │ └── django_logutils │ │ └── base.html └── utils.py ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── django_logutils.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── modules.rst ├── readme.rst └── usage.rst ├── manage.py ├── requirements ├── common.txt └── test.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── middleware │ ├── __init__.py │ ├── test_middleware.py │ ├── urls.py │ └── views.py ├── settings.py ├── test_simple.py └── test_utils.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | htmlcov 28 | nosetests.xml 29 | htmlcov 30 | 31 | # Translations 32 | *.mo 33 | 34 | # Mr Developer 35 | .mr.developer.cfg 36 | .project 37 | .pydevproject 38 | 39 | # Complexity 40 | output/*.html 41 | output/*/index.html 42 | 43 | # Sphinx 44 | docs/_build 45 | 46 | # Virtualenv 47 | .venv 48 | 49 | # Editor 50 | .idea 51 | 52 | # Cache 53 | .cache 54 | 55 | -------------------------------------------------------------------------------- /.pylint.cfg: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | 3 | # Specify a configuration file. 4 | #rcfile= 5 | 6 | # Python code to execute, usually for sys.path manipulation such as 7 | # pygtk.require(). 8 | #init-hook= 9 | 10 | # Profiled execution. 11 | profile=no 12 | 13 | # Add files or directories to the blacklist. They should be base names, not 14 | # paths. 15 | ignore=CVS 16 | 17 | # Pickle collected data for later comparisons. 18 | persistent=yes 19 | 20 | # List of plugins (as comma separated values of python modules names) to load, 21 | # usually to register additional checkers. 22 | load-plugins= 23 | 24 | # Deprecated. It was used to include message's id in output. Use --msg-template 25 | # instead. 26 | # include-ids=no 27 | 28 | # Deprecated. It was used to include symbolic ids of messages in output. Use 29 | # --msg-template instead. 30 | # symbols=no 31 | 32 | # Use multiple processes to speed up Pylint. 33 | jobs=1 34 | 35 | # Allow loading of arbitrary C extensions. Extensions are imported into the 36 | # active Python interpreter and may run arbitrary code. 37 | unsafe-load-any-extension=no 38 | 39 | # A comma-separated list of package or module names from where C extensions may 40 | # be loaded. Extensions are loading into the active Python interpreter and may 41 | # run arbitrary code 42 | extension-pkg-whitelist= 43 | 44 | # Allow optimization of some AST trees. This will activate a peephole AST 45 | # optimizer, which will apply various small optimizations. For instance, it can 46 | # be used to obtain the result of joining multiple strings with the addition 47 | # operator. Joining a lot of strings can lead to a maximum recursion error in 48 | # Pylint and this flag can prevent that. It has one side effect, the resulting 49 | # AST will be different than the one from reality. 50 | optimize-ast=no 51 | 52 | 53 | [MESSAGES CONTROL] 54 | 55 | # Only show warnings with the listed confidence levels. Leave empty to show 56 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED 57 | confidence= 58 | 59 | # Enable the message, report, category or checker with the given id(s). You can 60 | # either give multiple identifier separated by comma (,) or put this option 61 | # multiple time. See also the "--disable" option for examples. 62 | #enable= 63 | 64 | # Disable the message, report, category or checker with the given id(s). You 65 | # can either give multiple identifiers separated by comma (,) or put this 66 | # option multiple times (only on the command line, not in the configuration 67 | # file where it should appear only once).You can also use "--disable=all" to 68 | # disable everything first and then reenable specific checks. For example, if 69 | # you want to run only the similarities checker, you can use "--disable=all 70 | # --enable=similarities". If you want to run only the classes checker, but have 71 | # no Warning level messages displayed, use"--disable=all --enable=classes 72 | # --disable=W" 73 | disable=E1608,W1627,E1601,E1603,E1602,E1605,E1604,E1607,E1606,W1621,W1620,W1623,W1622,W1625,W1624,W1609,W1608,W1607,W1606,W1605,W1604,W1603,W1602,W1601,W1639,W1640,I0021,W1638,I0020,W1618,W1619,W1630,W1626,W1637,W1634,W1635,W1610,W1611,W1612,W1613,W1614,W1615,W1616,W1617,W1632,W1633,W0704,W1628,W1629,W1636 74 | 75 | 76 | [REPORTS] 77 | 78 | # Set the output format. Available formats are text, parseable, colorized, msvs 79 | # (visual studio) and html. You can also give a reporter class, eg 80 | # mypackage.mymodule.MyReporterClass. 81 | output-format=text 82 | 83 | # Put messages in a separate file for each module / package specified on the 84 | # command line instead of printing them on stdout. Reports (if any) will be 85 | # written in a file name "pylint_global.[txt|html]". 86 | files-output=no 87 | 88 | # Tells whether to display a full report or only the messages 89 | reports=yes 90 | 91 | # Python expression which should return a note less than 10 (10 is the highest 92 | # note). You have access to the variables errors warning, statement which 93 | # respectively contain the number of errors / warnings messages and the total 94 | # number of statements analyzed. This is used by the global evaluation report 95 | # (RP0004). 96 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 97 | 98 | # Add a comment according to your evaluation note. This is used by the global 99 | # evaluation report (RP0004). 100 | comment=no 101 | 102 | # Template used to display messages. This is a python new-style format string 103 | # used to format the message information. See doc for all details 104 | #msg-template= 105 | 106 | 107 | [BASIC] 108 | 109 | # Required attributes for module, separated by a comma 110 | required-attributes= 111 | 112 | # List of builtins function names that should not be used, separated by a comma 113 | bad-functions=map,filter,input 114 | 115 | # Good variable names which should always be accepted, separated by a comma 116 | good-names=i,j,k,ex,Run,_ 117 | 118 | # Bad variable names which should always be refused, separated by a comma 119 | bad-names=foo,bar,baz,toto,tutu,tata 120 | 121 | # Colon-delimited sets of names that determine each other's naming style when 122 | # the name regexes allow several styles. 123 | name-group= 124 | 125 | # Include a hint for the correct naming format with invalid-name 126 | include-naming-hint=no 127 | 128 | # Regular expression matching correct function names 129 | function-rgx=[a-z_][a-z0-9_]{2,30}$ 130 | 131 | # Naming hint for function names 132 | function-name-hint=[a-z_][a-z0-9_]{2,30}$ 133 | 134 | # Regular expression matching correct variable names 135 | variable-rgx=[a-z_][a-z0-9_]{2,30}$ 136 | 137 | # Naming hint for variable names 138 | variable-name-hint=[a-z_][a-z0-9_]{2,30}$ 139 | 140 | # Regular expression matching correct constant names 141 | const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ 142 | 143 | # Naming hint for constant names 144 | const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ 145 | 146 | # Regular expression matching correct attribute names 147 | attr-rgx=[a-z_][a-z0-9_]{2,30}$ 148 | 149 | # Naming hint for attribute names 150 | attr-name-hint=[a-z_][a-z0-9_]{2,30}$ 151 | 152 | # Regular expression matching correct argument names 153 | argument-rgx=[a-z_][a-z0-9_]{2,30}$ 154 | 155 | # Naming hint for argument names 156 | argument-name-hint=[a-z_][a-z0-9_]{2,30}$ 157 | 158 | # Regular expression matching correct class attribute names 159 | class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ 160 | 161 | # Naming hint for class attribute names 162 | class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ 163 | 164 | # Regular expression matching correct inline iteration names 165 | inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ 166 | 167 | # Naming hint for inline iteration names 168 | inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ 169 | 170 | # Regular expression matching correct class names 171 | class-rgx=[A-Z_][a-zA-Z0-9]+$ 172 | 173 | # Naming hint for class names 174 | class-name-hint=[A-Z_][a-zA-Z0-9]+$ 175 | 176 | # Regular expression matching correct module names 177 | module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ 178 | 179 | # Naming hint for module names 180 | module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ 181 | 182 | # Regular expression matching correct method names 183 | method-rgx=[a-z_][a-z0-9_]{2,30}$ 184 | 185 | # Naming hint for method names 186 | method-name-hint=[a-z_][a-z0-9_]{2,30}$ 187 | 188 | # Regular expression which should only match function or class names that do 189 | # not require a docstring. 190 | no-docstring-rgx=__.*__ 191 | 192 | # Minimum line length for functions/classes that require docstrings, shorter 193 | # ones are exempt. 194 | docstring-min-length=-1 195 | 196 | 197 | [FORMAT] 198 | 199 | # Maximum number of characters on a single line. 200 | max-line-length=100 201 | 202 | # Regexp for a line that is allowed to be longer than the limit. 203 | ignore-long-lines=^\s*(# )??$ 204 | 205 | # Allow the body of an if to be on the same line as the test if there is no 206 | # else. 207 | single-line-if-stmt=no 208 | 209 | # List of optional constructs for which whitespace checking is disabled 210 | no-space-check=trailing-comma,dict-separator 211 | 212 | # Maximum number of lines in a module 213 | max-module-lines=1000 214 | 215 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 216 | # tab). 217 | indent-string=' ' 218 | 219 | # Number of spaces of indent required inside a hanging or continued line. 220 | indent-after-paren=4 221 | 222 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 223 | expected-line-ending-format= 224 | 225 | 226 | [LOGGING] 227 | 228 | # Logging modules to check that the string format arguments are in logging 229 | # function parameter format 230 | logging-modules=logging 231 | 232 | 233 | [MISCELLANEOUS] 234 | 235 | # List of note tags to take in consideration, separated by a comma. 236 | notes=FIXME,XXX,TODO 237 | 238 | 239 | [SIMILARITIES] 240 | 241 | # Minimum lines number of a similarity. 242 | min-similarity-lines=4 243 | 244 | # Ignore comments when computing similarities. 245 | ignore-comments=yes 246 | 247 | # Ignore docstrings when computing similarities. 248 | ignore-docstrings=yes 249 | 250 | # Ignore imports when computing similarities. 251 | ignore-imports=no 252 | 253 | 254 | [SPELLING] 255 | 256 | # Spelling dictionary name. Available dictionaries: none. To make it working 257 | # install python-enchant package. 258 | spelling-dict= 259 | 260 | # List of comma separated words that should not be checked. 261 | spelling-ignore-words= 262 | 263 | # A path to a file that contains private dictionary; one word per line. 264 | spelling-private-dict-file= 265 | 266 | # Tells whether to store unknown words to indicated private dictionary in 267 | # --spelling-private-dict-file option instead of raising a message. 268 | spelling-store-unknown-words=no 269 | 270 | 271 | [TYPECHECK] 272 | 273 | # Tells whether missing members accessed in mixin class should be ignored. A 274 | # mixin class is detected if its name ends with "mixin" (case insensitive). 275 | ignore-mixin-members=yes 276 | 277 | # List of module names for which member attributes should not be checked 278 | # (useful for modules/projects where namespaces are manipulated during runtime 279 | # and thus existing member attributes cannot be deduced by static analysis 280 | ignored-modules= 281 | 282 | # List of classes names for which member attributes should not be checked 283 | # (useful for classes with attributes dynamically set). 284 | ignored-classes=SQLObject 285 | 286 | # When zope mode is activated, add a predefined set of Zope acquired attributes 287 | # to generated-members. 288 | zope=no 289 | 290 | # List of members which are set dynamically and missed by pylint inference 291 | # system, and so shouldn't trigger E0201 when accessed. Python regular 292 | # expressions are accepted. 293 | generated-members=REQUEST,acl_users,aq_parent,objects 294 | 295 | 296 | [VARIABLES] 297 | 298 | # Tells whether we should check for unused import in __init__ files. 299 | init-import=no 300 | 301 | # A regular expression matching the name of dummy variables (i.e. expectedly 302 | # not used). 303 | dummy-variables-rgx=_$|dummy 304 | 305 | # List of additional names supposed to be defined in builtins. Remember that 306 | # you should avoid to define new builtins when possible. 307 | additional-builtins= 308 | 309 | # List of strings which can identify a callback function by name. A callback 310 | # name must start or end with one of those strings. 311 | callbacks=cb_,_cb 312 | 313 | 314 | [CLASSES] 315 | 316 | # List of interface methods to ignore, separated by a comma. This is used for 317 | # instance to not check methods defines in Zope's Interface base class. 318 | ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by 319 | 320 | # List of method names used to declare (i.e. assign) instance attributes. 321 | defining-attr-methods=__init__,__new__,setUp 322 | 323 | # List of valid names for the first argument in a class method. 324 | valid-classmethod-first-arg=cls 325 | 326 | # List of valid names for the first argument in a metaclass class method. 327 | valid-metaclass-classmethod-first-arg=mcs 328 | 329 | # List of member names, which should be excluded from the protected access 330 | # warning. 331 | exclude-protected=_asdict,_fields,_replace,_source,_make 332 | 333 | 334 | [DESIGN] 335 | 336 | # Maximum number of arguments for function / method 337 | max-args=5 338 | 339 | # Argument names that match this expression will be ignored. Default to name 340 | # with leading underscore 341 | ignored-argument-names=_.* 342 | 343 | # Maximum number of locals for function / method body 344 | max-locals=15 345 | 346 | # Maximum number of return / yield for function / method body 347 | max-returns=6 348 | 349 | # Maximum number of branch for function / method body 350 | max-branches=12 351 | 352 | # Maximum number of statements in function / method body 353 | max-statements=50 354 | 355 | # Maximum number of parents for a class (see R0901). 356 | max-parents=7 357 | 358 | # Maximum number of attributes for a class (see R0902). 359 | max-attributes=7 360 | 361 | # Minimum number of public methods for a class (see R0903). 362 | min-public-methods=2 363 | 364 | # Maximum number of public methods for a class (see R0904). 365 | max-public-methods=20 366 | 367 | 368 | [IMPORTS] 369 | 370 | # Deprecated modules which should not be used, separated by a comma 371 | deprecated-modules=regsub,TERMIOS,Bastion,rexec 372 | 373 | # Create a graph of every (i.e. internal and external) dependencies in the 374 | # given file (report RP0402 must not be disabled) 375 | import-graph= 376 | 377 | # Create a graph of external dependencies in the given file (report RP0402 must 378 | # not be disabled) 379 | ext-import-graph= 380 | 381 | # Create a graph of internal dependencies in the given file (report RP0402 must 382 | # not be disabled) 383 | int-import-graph= 384 | 385 | 386 | [EXCEPTIONS] 387 | 388 | # Exceptions that will emit a warning when being caught. Defaults to 389 | # "Exception" 390 | overgeneral-exceptions=Exception 391 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | 3 | language: python 4 | 5 | python: 6 | - "3.6" 7 | - "3.5" 8 | - "3.4" 9 | - "2.7" 10 | 11 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 12 | install: pip install -r requirements/test.txt 13 | 14 | # command to run tests using coverage 15 | script: make test 16 | 17 | # report coverage to coveralls.io 18 | after_success: coveralls 19 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Sander Smits 9 | 10 | Contributors 11 | ------------ 12 | 13 | * Liam Andrew 14 | * Arjen Vrielink 15 | * Reinout van Rees 16 | * Carsten Byrman 17 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/jsmits/django-logutils/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | django-logutils could always use more documentation, whether as part of the 40 | official django-logutils docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github.com/jsmits/django-logutils/issues. 47 | 48 | If you are proposing a feature: 49 | 50 | * Explain in detail how it would work. 51 | * Keep the scope as narrow as possible, to make it easier to implement. 52 | * Remember that this is a volunteer-driven project, and that contributions 53 | are welcome :) 54 | 55 | Get Started! 56 | ------------ 57 | 58 | Ready to contribute? Here's how to set up `django-logutils` for local development. 59 | 60 | 1. Fork the `django-logutils` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/django-logutils.git 64 | 65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 66 | 67 | $ mkvirtualenv django-logutils 68 | $ cd django-logutils/ 69 | $ python setup.py develop 70 | 71 | 4. Create a branch for local development:: 72 | 73 | $ git checkout -b name-of-your-bugfix-or-feature 74 | 75 | Now you can make your changes locally. 76 | 77 | 5. When you're done making changes, check that your changes pass flake8 and the 78 | tests, including testing other Python versions with tox:: 79 | 80 | $ flake8 django_logutils tests 81 | $ python setup.py test 82 | $ tox 83 | 84 | To get flake8 and tox, just pip install them into your virtualenv. 85 | 86 | 6. Commit your changes and push your branch to GitHub:: 87 | 88 | $ git add . 89 | $ git commit -m "Your detailed description of your changes." 90 | $ git push origin name-of-your-bugfix-or-feature 91 | 92 | 7. Submit a pull request through the GitHub website. 93 | 94 | Pull Request Guidelines 95 | ----------------------- 96 | 97 | Before you submit a pull request, check that it meets these guidelines: 98 | 99 | 1. The pull request should include tests. 100 | 2. If the pull request adds functionality, the docs should be updated. Put 101 | your new functionality into a function with a docstring, and add the 102 | feature to the list in README.rst. 103 | 3. The pull request should work for Python 2.7, 3.4, 3.5 and 3.6. 104 | Check https://travis-ci.org/jsmits/django-logutils/pull_requests 105 | and make sure that the tests pass for all supported Python versions. 106 | 107 | Tips 108 | ---- 109 | 110 | To run a subset of tests:: 111 | 112 | $ python -m unittest tests.test_django_logutils 113 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 7 | 0.4.4 (unreleased) 8 | ++++++++++++++++++ 9 | 10 | - Nothing changed yet. 11 | 12 | 13 | 0.4.3 (2017-05-11) 14 | ++++++++++++++++++ 15 | 16 | - Make sure that log messages are aggregable by tools like Sentry. 17 | 18 | 19 | 0.4.2 (2015-10-30) 20 | ++++++++++++++++++ 21 | 22 | - Support StreamingHttpResponse that doesn't have content length. 23 | 24 | 25 | 0.4.1 (2015-08-21) 26 | ++++++++++++++++++ 27 | 28 | - Add tests for app settings. 29 | 30 | 31 | 0.4.0 (2015-08-20) 32 | ++++++++++++++++++ 33 | 34 | - Make ``REQUEST_TIME_THRESHOLD`` a setting. 35 | 36 | 37 | 0.3.1 (2015-08-04) 38 | ++++++++++++++++++ 39 | 40 | - Update documentation. 41 | 42 | 43 | 0.3.0 (2015-08-04) 44 | ++++++++++++++++++ 45 | 46 | - Add ``EventLogger`` class. 47 | 48 | 49 | 0.2.5 (2015-07-31) 50 | ++++++++++++++++++ 51 | 52 | - Reach 100% test coverage. 53 | 54 | 55 | 0.2.4 (2015-07-31) 56 | ++++++++++++++++++ 57 | 58 | - Improve project structure. 59 | 60 | 61 | 0.2.3 (2015-07-30) 62 | ++++++++++++++++++ 63 | 64 | - Add ``log_event`` utility function for logging events. 65 | 66 | 67 | 0.2.2 (2015-07-29) 68 | ++++++++++++++++++ 69 | 70 | - Add ``add_items_to_message`` utility function. 71 | 72 | 73 | 0.2.1 (2015-07-29) 74 | ++++++++++++++++++ 75 | 76 | - More and better tests. 77 | 78 | 79 | 0.2.0 (2015-07-28) 80 | ++++++++++++++++++ 81 | 82 | - Release replacing previous faulty dev release. 83 | 84 | 85 | 0.1.0 (2015-07-28) 86 | ++++++++++++++++++ 87 | 88 | * First release on PyPI. 89 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015, Sander Smits 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 9 | 10 | * Neither the name of django-logutils nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | recursive-include django_logutils *.html *.png *.gif *js *.css *jpg *jpeg *svg *py 7 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs 2 | 3 | help: 4 | @echo "clean-build - remove build artifacts" 5 | @echo "clean-pyc - remove python file artifacts" 6 | @echo "clean - run clean-build and clean-pyc" 7 | @echo "lint - check style with flake8 and pylint" 8 | @echo "test - run tests quickly with the default python" 9 | @echo "test-all - run tests on every python version with tox" 10 | @echo "coverage - check code coverage quickly with the default python" 11 | @echo "docs - generate Sphinx HTML documentation, including API docs" 12 | @echo "release - make a release with zest.releaser's fullrelease" 13 | 14 | clean: clean-build clean-pyc 15 | 16 | clean-build: 17 | rm -fr build/ 18 | rm -fr dist/ 19 | rm -fr *.egg-info 20 | 21 | clean-pyc: 22 | find . -name '*.pyc' -exec rm -f {} + 23 | find . -name '*.pyo' -exec rm -f {} + 24 | find . -name '*~' -exec rm -f {} + 25 | 26 | flake8: 27 | flake8 django_logutils tests --max-complexity 10 --exit-zero 28 | 29 | lint: flake8 30 | pylint --load-plugins pylint_django -f colorized --rcfile=.pylint.cfg --disable=I0011 -j 4 -r n django_logutils/ tests/ 31 | 32 | test: 33 | coverage run --source django_logutils -m py.test -v --ignore=lib/ 34 | coverage report -m 35 | 36 | test-all: 37 | tox 38 | 39 | coverage: test 40 | coverage html 41 | open htmlcov/index.html 42 | 43 | docs: 44 | export DJANGO_SETTINGS_MODULE=tests.settings 45 | rm -f docs/django-logutils.rst 46 | rm -f docs/modules.rst 47 | sphinx-apidoc -o docs/ django_logutils 48 | $(MAKE) -C docs clean 49 | $(MAKE) -C docs html 50 | open docs/_build/html/index.html 51 | 52 | release: 53 | fullrelease 54 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============================= 2 | django-logutils 3 | ============================= 4 | 5 | .. image:: https://badge.fury.io/py/django-logutils.png 6 | :target: https://badge.fury.io/py/django-logutils 7 | 8 | .. image:: https://travis-ci.org/jsmits/django-logutils.png?branch=master 9 | :target: https://travis-ci.org/jsmits/django-logutils 10 | 11 | .. image:: https://readthedocs.org/projects/django-logutils/badge/?version=latest 12 | :target: https://readthedocs.org/projects/django-logutils/?badge=latest 13 | :alt: Documentation Status 14 | 15 | .. image:: https://coveralls.io/repos/jsmits/django-logutils/badge.svg?branch=master&service=github 16 | :target: https://coveralls.io/github/jsmits/django-logutils?branch=master 17 | 18 | Various logging-related utilities for Django projects. For now, it provides 19 | a LoggingMiddleware class and an EventLogger class. 20 | 21 | Documentation 22 | ------------- 23 | 24 | http://django-logutils.readthedocs.org 25 | 26 | Quickstart 27 | ---------- 28 | 29 | Install django-logutils:: 30 | 31 | pip install django-logutils 32 | 33 | LoggingMiddleware 34 | ----------------- 35 | 36 | LoggingMiddleware is middleware class for Django, that logs extra 37 | request-related information. To use it in your Django projects, add it to 38 | your ``MIDDLEWARE_CLASSES`` setting:: 39 | 40 | MIDDLEWARE_CLASSES = ( 41 | ... 42 | 'django_logutils.middleware.LoggingMiddleware', 43 | ... 44 | ) 45 | 46 | The extra information consists of: 47 | 48 | - event (default: 'request') 49 | 50 | - remote ip address: the remote ip address of the user doing the request. 51 | 52 | - user email: the email address of the requesting user, if available 53 | 54 | - request method: post or get 55 | 56 | - request url path 57 | 58 | - response status code 59 | 60 | - content length of the response body 61 | 62 | - request time 63 | 64 | N.B.: event can be overriden by using the ``LOGUTILS_LOGGING_MIDDLEWARE_EVENT`` 65 | setting in your project. 66 | 67 | The log message itself is a string composed of the remote ip address, the user 68 | email, the request method, the request url, the status code, the content 69 | length of the body and the request time. Additionally, a dictionary with the 70 | log items are added as an extra keyword argument when sending a logging 71 | statement. 72 | 73 | If settings.DEBUG is True or the request time is more than 1 second, two 74 | additional parameters are added to the logging dictionary: ``nr_queries`` that 75 | represents the number of queries executed during the request-response cycle 76 | and ``sql_time`` that represents the time it took to execute those queries. 77 | Slow requests are also raised to a loglevel of ``WARNING``. 78 | 79 | N.B.: the time threshold for slow requests can be overriden by using the 80 | ``LOGUTILS_REQUEST_TIME_THRESHOLD`` setting in your project. 81 | 82 | EventLogger 83 | ----------- 84 | 85 | The EventLogger class makes it easy to create dictionary-based logging 86 | statements, that can be used by log processors like Logstash. Log events can be 87 | used to track metrics and/or to create visualisations. 88 | 89 | Here's an example of how you can use it:: 90 | 91 | >>> from django_logutils.utils import EventLogger 92 | >>> log_event = EventLogger('my_logger') 93 | >>> log_event('my_event', {'action': 'push_button'}) 94 | 95 | Development 96 | ----------- 97 | 98 | Install the test requirements:: 99 | 100 | $ pip install -r requirements/test.txt 101 | 102 | Run the tests to check everything is fine:: 103 | 104 | $ make test 105 | 106 | To run the tests and opening the coverage html in your browser:: 107 | 108 | $ make coverage 109 | 110 | To run flake8 and pylint, do:: 111 | 112 | $ make lint 113 | 114 | To generate the documentation, do:: 115 | 116 | $ make docs 117 | -------------------------------------------------------------------------------- /django_logutils/__init__.py: -------------------------------------------------------------------------------- 1 | """Package for `django_logutils``.""" 2 | __version__ = '0.4.4.dev0' 3 | -------------------------------------------------------------------------------- /django_logutils/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.conf import settings # noqa 3 | from appconf import AppConf 4 | 5 | 6 | class LogutilsAppConf(AppConf): 7 | LOGGING_MIDDLEWARE_EVENT = 'request' 8 | REQUEST_TIME_THRESHOLD = 1. 9 | 10 | class Meta: 11 | prefix = 'logutils' 12 | -------------------------------------------------------------------------------- /django_logutils/middleware.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import 3 | from __future__ import division 4 | from __future__ import print_function 5 | from __future__ import unicode_literals 6 | 7 | import logging 8 | import time 9 | 10 | from django.db import connection 11 | 12 | from django_logutils.conf import settings 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | def create_log_dict(request, response): 18 | """ 19 | Create a dictionary with logging data. 20 | """ 21 | remote_addr = request.META.get('REMOTE_ADDR') 22 | if remote_addr in getattr(settings, 'INTERNAL_IPS', []): 23 | remote_addr = request.META.get( 24 | 'HTTP_X_FORWARDED_FOR') or remote_addr 25 | 26 | user_email = "-" 27 | if hasattr(request, 'user'): 28 | user_email = getattr(request.user, 'email', '-') 29 | 30 | if response.streaming: 31 | content_length = 'streaming' 32 | else: 33 | content_length = len(response.content) 34 | 35 | return { 36 | # 'event' makes event-based filtering possible in logging backends 37 | # like logstash 38 | 'event': settings.LOGUTILS_LOGGING_MIDDLEWARE_EVENT, 39 | 'remote_address': remote_addr, 40 | 'user_email': user_email, 41 | 'method': request.method, 42 | 'url': request.get_full_path(), 43 | 'status': response.status_code, 44 | 'content_length': content_length, 45 | 'request_time': -1, # NA value: real value added by LoggingMiddleware 46 | } 47 | 48 | 49 | def create_log_message(log_dict, use_sql_info=False, fmt=True): 50 | """ 51 | Create the logging message string. 52 | """ 53 | log_msg = ( 54 | "%(remote_address)s %(user_email)s %(method)s %(url)s %(status)d " 55 | "%(content_length)d (%(request_time).2f seconds)" 56 | ) 57 | if use_sql_info: 58 | sql_time = sum( 59 | float(q['time']) for q in connection.queries) * 1000 60 | extra_log = { 61 | 'nr_queries': len(connection.queries), 62 | 'sql_time': sql_time} 63 | log_msg += " (%(nr_queries)d SQL queries, %(sql_time)f ms)" 64 | log_dict.update(extra_log) 65 | return log_msg % log_dict if fmt else log_msg 66 | 67 | 68 | class LoggingMiddleware(object): 69 | """ 70 | Capture request info and logs it. 71 | 72 | Logs all requests with log level info. If request take longer than 73 | REQUEST_TIME_THRESHOLD, log level warningis used. 74 | 75 | Logging middleware that captures the following: 76 | * logging event. 77 | * remote address (whether proxied or direct). 78 | * if authenticated, then user email address. 79 | * request method (GET/POST etc). 80 | * request full path. 81 | * response status code (200, 404 etc). 82 | * content length. 83 | * request process time. 84 | * if DEBUG=True or REQUEST_TIME_THRESHOLD is exceeded, also logs SQL 85 | query information - number of queries and how long they too. 86 | 87 | Based on: https://djangosnippets.org/snippets/2624/ 88 | 89 | """ 90 | def __init__(self, *args, **kwargs): 91 | """ 92 | Add initial empty start_time. 93 | """ 94 | self.start_time = None 95 | 96 | def process_request(self, request): 97 | """ 98 | Add start time to request. 99 | """ 100 | self.start_time = time.time() 101 | 102 | def process_response(self, request, response): 103 | """ 104 | Create the logging message.. 105 | """ 106 | try: 107 | log_dict = create_log_dict(request, response) 108 | 109 | # add the request time to the log_dict; if no start time is 110 | # available, use -1 as NA value 111 | request_time = ( 112 | time.time() - self.start_time if hasattr(self, 'start_time') 113 | and self.start_time else -1) 114 | log_dict.update({'request_time': request_time}) 115 | 116 | is_request_time_too_high = ( 117 | request_time > float(settings.LOGUTILS_REQUEST_TIME_THRESHOLD)) 118 | use_sql_info = settings.DEBUG or is_request_time_too_high 119 | 120 | log_msg = create_log_message(log_dict, use_sql_info, fmt=False) 121 | 122 | if is_request_time_too_high: 123 | logger.warning(log_msg, log_dict, extra=log_dict) 124 | else: 125 | logger.info(log_msg, log_dict, extra=log_dict) 126 | except Exception as e: 127 | logger.exception(e) 128 | 129 | return response 130 | -------------------------------------------------------------------------------- /django_logutils/models.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsmits/django-logutils/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/django_logutils/models.py -------------------------------------------------------------------------------- /django_logutils/static/css/django_logutils.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsmits/django-logutils/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/django_logutils/static/css/django_logutils.css -------------------------------------------------------------------------------- /django_logutils/static/img/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsmits/django-logutils/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/django_logutils/static/img/.gitignore -------------------------------------------------------------------------------- /django_logutils/static/js/django_logutils.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsmits/django-logutils/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/django_logutils/static/js/django_logutils.js -------------------------------------------------------------------------------- /django_logutils/templates/django_logutils/base.html: -------------------------------------------------------------------------------- 1 | 2 | {% comment %} 3 | As the developer of this package, don't place anything here if you can help it 4 | since this allows developers to have interoperability between your template 5 | structure and their own. 6 | 7 | Example: Developer melding the 2SoD pattern to fit inside with another pattern:: 8 | 9 | {% extends "base.html" %} 10 | {% load static %} 11 | 12 | 13 | {% block extra_js %} 14 | 15 | 16 | {% block javascript %} 17 | 18 | {% endblock javascript %} 19 | 20 | {% endblock extra_js %} 21 | {% endcomment %} 22 | -------------------------------------------------------------------------------- /django_logutils/utils.py: -------------------------------------------------------------------------------- 1 | """Various utility functions.""" 2 | import logging 3 | 4 | 5 | root_logger = logging.getLogger() 6 | 7 | 8 | def add_items_to_message(msg, log_dict): 9 | """Utility function to add dictionary items to a log message.""" 10 | out = msg 11 | for key, value in log_dict.items(): 12 | out += " {}={}".format(key, value) 13 | return out 14 | 15 | 16 | def log_event(event, logger=root_logger, **log_dict): 17 | """ 18 | Utility function for logging an event (e.g. for metric analysis). 19 | 20 | If no logger is given, fallback to the root logger. 21 | 22 | """ 23 | msg = "event={}".format(event) 24 | msg = add_items_to_message(msg, log_dict) 25 | log_dict.update({'event': event}) 26 | logger.info(msg, extra=log_dict) 27 | 28 | 29 | class EventLogger(object): 30 | """ 31 | EventLogger class that wrap the log_event function by optionally using an 32 | existing logger. 33 | 34 | Usage: 35 | >>> log_event = EventLogger('my_logger') 36 | >>> log_event('my_event', {'action': 'push_button'}) 37 | 38 | """ 39 | def __init__(self, logger_name=None, *args, **kwargs): 40 | """Initialize the EventLogger 41 | 42 | :param logger_name: name of the logger, e.g. 'my_logger' or __name__ 43 | """ 44 | if logger_name: 45 | self.logger = logging.getLogger(logger_name) 46 | else: 47 | self.logger = root_logger 48 | 49 | def __call__(self, event, *args, **log_dict): 50 | """Call the log_event function.""" 51 | log_event(event, logger=self.logger, **log_dict) 52 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # complexity documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | cwd = os.getcwd() 22 | parent = os.path.dirname(cwd) 23 | sys.path.append(parent) 24 | 25 | import django_logutils 26 | 27 | # -- General configuration ----------------------------------------------------- 28 | 29 | # If your documentation needs a minimal Sphinx version, state it here. 30 | #needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be extensions 33 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix of source filenames. 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'django-logutils' 50 | copyright = u'2015, Sander Smits' 51 | 52 | # The version info for the project you're documenting, acts as replacement for 53 | # |version| and |release|, also used in various other places throughout the 54 | # built documents. 55 | # 56 | # The short X.Y version. 57 | version = django_logutils.__version__ 58 | # The full version, including alpha/beta/rc tags. 59 | release = django_logutils.__version__ 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | #language = None 64 | 65 | # There are two options for replacing |today|: either, you set today to some 66 | # non-false value, then it is used: 67 | #today = '' 68 | # Else, today_fmt is used as the format for a strftime call. 69 | #today_fmt = '%B %d, %Y' 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | exclude_patterns = ['_build'] 74 | 75 | # The reST default role (used for this markup: `text`) to use for all documents. 76 | #default_role = None 77 | 78 | # If true, '()' will be appended to :func: etc. cross-reference text. 79 | #add_function_parentheses = True 80 | 81 | # If true, the current module name will be prepended to all description 82 | # unit titles (such as .. function::). 83 | #add_module_names = True 84 | 85 | # If true, sectionauthor and moduleauthor directives will be shown in the 86 | # output. They are ignored by default. 87 | #show_authors = False 88 | 89 | # The name of the Pygments (syntax highlighting) style to use. 90 | pygments_style = 'sphinx' 91 | 92 | # A list of ignored prefixes for module index sorting. 93 | #modindex_common_prefix = [] 94 | 95 | # If true, keep warnings as "system message" paragraphs in the built documents. 96 | #keep_warnings = False 97 | 98 | 99 | # -- Options for HTML output --------------------------------------------------- 100 | 101 | # The theme to use for HTML and HTML Help pages. See the documentation for 102 | # a list of builtin themes. 103 | html_theme = 'sphinx_rtd_theme' 104 | 105 | # Theme options are theme-specific and customize the look and feel of a theme 106 | # further. For a list of options available for each theme, see the 107 | # documentation. 108 | #html_theme_options = {} 109 | 110 | # Add any paths that contain custom themes here, relative to this directory. 111 | #html_theme_path = [] 112 | 113 | # The name for this set of Sphinx documents. If None, it defaults to 114 | # " v documentation". 115 | #html_title = None 116 | 117 | # A shorter title for the navigation bar. Default is the same as html_title. 118 | #html_short_title = None 119 | 120 | # The name of an image file (relative to this directory) to place at the top 121 | # of the sidebar. 122 | #html_logo = None 123 | 124 | # The name of an image file (within the static path) to use as favicon of the 125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 126 | # pixels large. 127 | #html_favicon = None 128 | 129 | # Add any paths that contain custom static files (such as style sheets) here, 130 | # relative to this directory. They are copied after the builtin static files, 131 | # so a file named "default.css" will overwrite the builtin "default.css". 132 | html_static_path = ['_static'] 133 | 134 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 135 | # using the given strftime format. 136 | #html_last_updated_fmt = '%b %d, %Y' 137 | 138 | # If true, SmartyPants will be used to convert quotes and dashes to 139 | # typographically correct entities. 140 | #html_use_smartypants = True 141 | 142 | # Custom sidebar templates, maps document names to template names. 143 | #html_sidebars = {} 144 | 145 | # Additional templates that should be rendered to pages, maps page names to 146 | # template names. 147 | #html_additional_pages = {} 148 | 149 | # If false, no module index is generated. 150 | #html_domain_indices = True 151 | 152 | # If false, no index is generated. 153 | #html_use_index = True 154 | 155 | # If true, the index is split into individual pages for each letter. 156 | #html_split_index = False 157 | 158 | # If true, links to the reST sources are added to the pages. 159 | #html_show_sourcelink = True 160 | 161 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 162 | #html_show_sphinx = True 163 | 164 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 165 | #html_show_copyright = True 166 | 167 | # If true, an OpenSearch description file will be output, and all pages will 168 | # contain a tag referring to it. The value of this option must be the 169 | # base URL from which the finished HTML is served. 170 | #html_use_opensearch = '' 171 | 172 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 173 | #html_file_suffix = None 174 | 175 | # Output file base name for HTML help builder. 176 | htmlhelp_basename = 'django-logutilsdoc' 177 | 178 | 179 | # -- Options for LaTeX output -------------------------------------------------- 180 | 181 | latex_elements = { 182 | # The paper size ('letterpaper' or 'a4paper'). 183 | #'papersize': 'letterpaper', 184 | 185 | # The font size ('10pt', '11pt' or '12pt'). 186 | #'pointsize': '10pt', 187 | 188 | # Additional stuff for the LaTeX preamble. 189 | #'preamble': '', 190 | } 191 | 192 | # Grouping the document tree into LaTeX files. List of tuples 193 | # (source start file, target name, title, author, documentclass [howto/manual]). 194 | latex_documents = [ 195 | ('index', 'django-logutils.tex', u'django-logutils Documentation', 196 | u'Sander Smits', 'manual'), 197 | ] 198 | 199 | # The name of an image file (relative to this directory) to place at the top of 200 | # the title page. 201 | #latex_logo = None 202 | 203 | # For "manual" documents, if this is true, then toplevel headings are parts, 204 | # not chapters. 205 | #latex_use_parts = False 206 | 207 | # If true, show page references after internal links. 208 | #latex_show_pagerefs = False 209 | 210 | # If true, show URL addresses after external links. 211 | #latex_show_urls = False 212 | 213 | # Documents to append as an appendix to all manuals. 214 | #latex_appendices = [] 215 | 216 | # If false, no module index is generated. 217 | #latex_domain_indices = True 218 | 219 | 220 | # -- Options for manual page output -------------------------------------------- 221 | 222 | # One entry per manual page. List of tuples 223 | # (source start file, name, description, authors, manual section). 224 | man_pages = [ 225 | ('index', 'django-logutils', u'django-logutils Documentation', 226 | [u'Sander Smits'], 1) 227 | ] 228 | 229 | # If true, show URL addresses after external links. 230 | #man_show_urls = False 231 | 232 | 233 | # -- Options for Texinfo output ------------------------------------------------ 234 | 235 | # Grouping the document tree into Texinfo files. List of tuples 236 | # (source start file, target name, title, author, 237 | # dir menu entry, description, category) 238 | texinfo_documents = [ 239 | ('index', 'django-logutils', u'django-logutils Documentation', 240 | u'Sander Smits', 'django-logutils', 'One line description of project.', 241 | 'Miscellaneous'), 242 | ] 243 | 244 | # Documents to append as an appendix to all manuals. 245 | #texinfo_appendices = [] 246 | 247 | # If false, no module index is generated. 248 | #texinfo_domain_indices = True 249 | 250 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 251 | #texinfo_show_urls = 'footnote' 252 | 253 | # If true, do not generate a @detailmenu in the "Top" node's menu. 254 | #texinfo_no_detailmenu = False 255 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/django_logutils.rst: -------------------------------------------------------------------------------- 1 | django_logutils package 2 | ======================= 3 | 4 | Submodules 5 | ---------- 6 | 7 | django_logutils.middleware module 8 | --------------------------------- 9 | 10 | .. automodule:: django_logutils.middleware 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | django_logutils.models module 16 | ----------------------------- 17 | 18 | .. automodule:: django_logutils.models 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | django_logutils.utils module 24 | ---------------------------- 25 | 26 | .. automodule:: django_logutils.utils 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | 32 | Module contents 33 | --------------- 34 | 35 | .. automodule:: django_logutils 36 | :members: 37 | :undoc-members: 38 | :show-inheritance: 39 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. complexity documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to django-logutils's documentation! 7 | ================================================================= 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | contributing 18 | authors 19 | history 20 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | At the command line:: 6 | 7 | $ easy_install django-logutils 8 | 9 | Or, if you have virtualenvwrapper installed:: 10 | 11 | $ mkvirtualenv django-logutils 12 | $ pip install django-logutils 13 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/modules.rst: -------------------------------------------------------------------------------- 1 | django_logutils 2 | =============== 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | django_logutils 8 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Usage 3 | ======== 4 | 5 | To use django-logutils in a project:: 6 | 7 | import django_logutils 8 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | 6 | if __name__ == '__main__': 7 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings') 9 | 10 | from django.core.management import execute_from_command_line 11 | 12 | execute_from_command_line(sys.argv) 13 | -------------------------------------------------------------------------------- /requirements/common.txt: -------------------------------------------------------------------------------- 1 | django>=1.5.1 2 | django-appconf>=1.0.1 3 | wheel==0.24.0 4 | -------------------------------------------------------------------------------- /requirements/test.txt: -------------------------------------------------------------------------------- 1 | -r common.txt 2 | 3 | coverage>=3.7.1 4 | coveralls>=0.5 5 | factory-boy==2.5.2 6 | flake8>=2.1.0 7 | mock>=1.0.1 8 | pylint>=1.4.3 9 | pylint-django>=0.6.1 10 | pytest>=2.7.2 11 | pytest-capturelog>=0.7 12 | pytest-django>=2.8.0 13 | pytest-xdist>=1.12 14 | sphinx>=1.3.1 15 | tox>=1.7.0 16 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | 4 | [pytest] 5 | DJANGO_SETTINGS_MODULE = tests.settings 6 | norecursedirs = .* requirements _build docs tmp* *.egg* htmlcov 7 | 8 | [zest.releaser] 9 | python-file-with-version = django_logutils/__init__.py 10 | create-wheel = yes 11 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import django_logutils 4 | 5 | try: 6 | from setuptools import setup 7 | except ImportError: 8 | from distutils.core import setup 9 | 10 | version = django_logutils.__version__ 11 | 12 | readme = open('README.rst').read() 13 | history = open('HISTORY.rst').read().replace('.. :changelog:', '') 14 | 15 | setup( 16 | name='django-logutils', 17 | version=version, 18 | description="""Various logging-related utilities for Django projects.""", 19 | long_description=readme + '\n\n' + history, 20 | author='Sander Smits', 21 | author_email='jhmsmits@gmail.com', 22 | url='https://github.com/jsmits/django-logutils', 23 | packages=[ 24 | 'django_logutils', 25 | ], 26 | include_package_data=True, 27 | install_requires=[ 28 | 'django', 29 | 'django-appconf' 30 | ], 31 | license="BSD", 32 | zip_safe=False, 33 | keywords='django-logutils', 34 | classifiers=[ 35 | 'Development Status :: 4 - Beta', 36 | 'Framework :: Django', 37 | 'Intended Audience :: Developers', 38 | 'License :: OSI Approved :: BSD License', 39 | 'Natural Language :: English', 40 | 'Programming Language :: Python :: 2', 41 | 'Programming Language :: Python :: 2.7', 42 | 'Programming Language :: Python :: 3', 43 | 'Programming Language :: Python :: 3.4', 44 | 'Programming Language :: Python :: 3.5', 45 | 'Programming Language :: Python :: 3.6', 46 | ], 47 | ) 48 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsmits/django-logutils/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/tests/__init__.py -------------------------------------------------------------------------------- /tests/middleware/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsmits/django-logutils/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/tests/middleware/__init__.py -------------------------------------------------------------------------------- /tests/middleware/test_middleware.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | from mock import Mock 4 | from mock import patch 5 | import pytest 6 | 7 | from django.http import HttpRequest 8 | from django.http import HttpResponse 9 | from django.http import StreamingHttpResponse 10 | 11 | from django_logutils import middleware 12 | 13 | 14 | @pytest.fixture 15 | def base_settings(settings): 16 | settings.MIDDLEWARE_CLASSES = ( 17 | 'django_logutils.middleware.LoggingMiddleware',) 18 | settings.ROOT_URLCONF = 'tests.middleware.urls' 19 | return settings 20 | 21 | 22 | def test_log_dict(): 23 | request = HttpRequest() 24 | response = HttpResponse() 25 | log_dict = middleware.create_log_dict(request, response) 26 | assert len(log_dict) == 8 27 | 28 | 29 | def test_empty_log_message(): 30 | request = HttpRequest() 31 | response = HttpResponse() 32 | log_dict = middleware.create_log_dict(request, response) 33 | log_msg = middleware.create_log_message(log_dict) 34 | # assert that log_msg is an empty log message 35 | assert log_msg == 'None - None 200 0 (-1.00 seconds)' 36 | 37 | 38 | def test_empty_logging_middleware_response(): 39 | request = HttpRequest() 40 | response = HttpResponse() 41 | lmw = middleware.LoggingMiddleware() 42 | lmw.process_request(request) 43 | response = lmw.process_response(request, response) 44 | assert response.status_code == 200 45 | 46 | 47 | @patch('django_logutils.middleware.logger') 48 | def test_streaming_http_response(mock_logger): 49 | request = HttpRequest() 50 | response = StreamingHttpResponse() 51 | lmw = middleware.LoggingMiddleware() 52 | lmw.process_request(request) 53 | lmw.process_response(request, response) 54 | assert (mock_logger.info.call_args[1]['extra']['content_length'] == 55 | 'streaming') 56 | 57 | 58 | def test_logging_middleware_request_start_time(): 59 | request = HttpRequest() 60 | lmw = middleware.LoggingMiddleware() 61 | assert lmw.start_time is None 62 | current_time = time.time() 63 | lmw.process_request(request) 64 | # current_time and start_time should be not differ by more than 3 seconds 65 | assert lmw.start_time - current_time < 3 66 | assert isinstance(lmw.start_time, float) 67 | 68 | 69 | def test_logging_middleware_with_empty_view(client, base_settings, caplog): 70 | response = client.get('/empty/', {}) 71 | assert len(response.content) == 0 72 | assert len(caplog.records()) == 1 73 | record = caplog.records()[0] 74 | message = record.msg % record.args 75 | assert '/empty/' in message 76 | assert '127.0.0.1' in message 77 | assert record.remote_address == '127.0.0.1' 78 | assert record.levelname == 'INFO' 79 | assert record.method == 'GET' 80 | assert record.filename == 'middleware.py' 81 | assert record.status == 200 82 | assert record.user_email == '-' 83 | assert record.url == '/empty/' 84 | 85 | 86 | def test_http_x_forwarded_for_header(client, base_settings, caplog): 87 | base_settings.INTERNAL_IPS = ('127.0.0.1', ) 88 | client.get('/empty/', {}, HTTP_X_FORWARDED_FOR='1.2.3.4') 89 | record = caplog.records()[0] 90 | assert record.remote_address == '1.2.3.4' 91 | 92 | 93 | def test_http_x_forwarded_for_header_without_internal_ips( 94 | client, base_settings, caplog): 95 | client.get('/empty/', {}, HTTP_X_FORWARDED_FOR='1.2.3.4') 96 | record = caplog.records()[0] 97 | assert record.remote_address == '127.0.0.1' 98 | 99 | 100 | def test_debug_logging(client, base_settings, caplog): 101 | base_settings.DEBUG = True 102 | client.get('/empty/') 103 | record = caplog.records()[0] 104 | assert hasattr(record, 'nr_queries') 105 | assert record.nr_queries == 0 106 | assert hasattr(record, 'sql_time') 107 | assert record.sql_time == 0 108 | 109 | 110 | def test_no_debug_logging_missing_keys(client, base_settings, caplog): 111 | base_settings.DEBUG = False 112 | client.get('/empty/') 113 | record = caplog.records()[0] 114 | assert not hasattr(record, 'nr_queries') 115 | assert not hasattr(record, 'sql_time') 116 | 117 | 118 | def test_logging_middleware_with_non_empty_view(client, base_settings): 119 | response = client.get('/non_empty/') 120 | assert len(response.content) == 5 121 | 122 | 123 | def test_logging_middleware_with_user_email(caplog): 124 | request = HttpRequest() 125 | request.user = Mock() 126 | request.user.email = 'john@example.com' 127 | lmw = middleware.LoggingMiddleware() 128 | lmw.process_response(request, HttpResponse()) 129 | record = caplog.records()[0] 130 | assert record.user_email == 'john@example.com' 131 | 132 | 133 | def test_loglevel_warning_if_request_threshold_exceeded(caplog): 134 | lmw = middleware.LoggingMiddleware() 135 | # put the request back in time to exceed the default threshold 136 | lmw.start_time = time.time() - 2 137 | lmw.process_response(HttpRequest(), HttpResponse()) 138 | record = caplog.records()[0] 139 | assert record.levelname == 'WARNING' 140 | 141 | 142 | def test_request_time_threshold_exceeded(client, base_settings, caplog): 143 | lmw = middleware.LoggingMiddleware() 144 | base_settings.LOGUTILS_REQUEST_TIME_THRESHOLD = 0.1 145 | # put the request back in time to exceed the threshold 146 | lmw.start_time = time.time() - 0.2 147 | lmw.process_response(HttpRequest(), HttpResponse()) 148 | record = caplog.records()[0] 149 | assert record.levelname == 'WARNING' 150 | 151 | 152 | def test_request_time_threshold_not_exceeded(client, base_settings, caplog): 153 | lmw = middleware.LoggingMiddleware() 154 | base_settings.LOGUTILS_REQUEST_TIME_THRESHOLD = 0.3 155 | lmw.start_time = time.time() - 0.2 156 | lmw.process_response(HttpRequest(), HttpResponse()) 157 | record = caplog.records()[0] 158 | assert record.levelname == 'INFO' 159 | 160 | 161 | def test_logging_middleware_process_response_exception(caplog): 162 | lmw = middleware.LoggingMiddleware() 163 | # force an AttributeError by using None as response 164 | lmw.process_response(HttpRequest(), None) 165 | record = caplog.records()[0] 166 | assert record.levelname == 'ERROR' 167 | 168 | 169 | def test_default_logging_middleware_event_setting( 170 | client, base_settings, caplog): 171 | client.get('/empty/') 172 | record = caplog.records()[0] 173 | assert record.event == 'request' 174 | 175 | 176 | def test_custom_logging_middleware_event_setting( 177 | client, base_settings, caplog): 178 | base_settings.LOGUTILS_LOGGING_MIDDLEWARE_EVENT = 'my_request' 179 | client.get('/empty/') 180 | record = caplog.records()[0] 181 | assert record.event == 'my_request' 182 | -------------------------------------------------------------------------------- /tests/middleware/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | url(r'^empty/$', views.empty_view), 7 | url(r'^non_empty/$', views.non_empty_view), 8 | ] 9 | -------------------------------------------------------------------------------- /tests/middleware/views.py: -------------------------------------------------------------------------------- 1 | from django.http import HttpResponse 2 | 3 | 4 | def empty_view(request, *args, **kwargs): 5 | return HttpResponse('') 6 | 7 | 8 | def non_empty_view(request, *args, **kwargs): 9 | return HttpResponse('dummy') 10 | -------------------------------------------------------------------------------- /tests/settings.py: -------------------------------------------------------------------------------- 1 | DEBUG = True 2 | 3 | USE_TZ = True 4 | 5 | DATABASES = { 6 | "default": { 7 | "ENGINE": "django.db.backends.sqlite3", 8 | } 9 | } 10 | 11 | INSTALLED_APPS = [ 12 | "django.contrib.auth", 13 | "django.contrib.contenttypes", 14 | "django.contrib.sites", 15 | "django_logutils", 16 | ] 17 | 18 | SITE_ID = 1 19 | 20 | MIDDLEWARE_CLASSES = () 21 | 22 | SECRET_KEY = 'abcdef' 23 | -------------------------------------------------------------------------------- /tests/test_simple.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=redefined-outer-name 2 | """Simple smoke test file.""" 3 | 4 | 5 | def test_smoke(): 6 | """Simple assertion smoke test.""" 7 | one = 1 8 | two = 2 9 | assert one + two == 3 10 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | from django_logutils.utils import add_items_to_message, log_event, EventLogger 2 | 3 | 4 | def test_add_items_to_message(): 5 | msg = "log message" 6 | items = {'user': 'benny', 'email': 'benny@example.com'} 7 | msg = add_items_to_message(msg, items) 8 | assert msg.startswith('log message') 9 | assert 'user=benny' in msg 10 | assert 'email=benny@example.com' in msg 11 | 12 | 13 | def test_add_items_to_message_with_empty_items(): 14 | msg = "log message" 15 | items = {} 16 | msg = add_items_to_message(msg, items) 17 | assert msg == 'log message' 18 | 19 | 20 | def test_log_event(caplog): 21 | log_event('testevent', **{'type': 'type_1', 'time': 123456}) 22 | assert len(caplog.records()) == 1 23 | record = caplog.records()[0] 24 | assert 'event=testevent' in record.msg 25 | assert 'type=type_1' in record.msg 26 | assert 'time=123456' in record.msg 27 | 28 | 29 | def test_event_logger(caplog): 30 | log_event = EventLogger('my_logger') 31 | log_event('testevent', **{'type': 'type_1', 'time': 123456}) 32 | assert len(caplog.records()) == 1 33 | record = caplog.records()[0] 34 | assert 'event=testevent' in record.msg 35 | assert 'type=type_1' in record.msg 36 | assert 'time=123456' in record.msg 37 | 38 | 39 | def test_event_logger_with_root_logger(caplog): 40 | log_event = EventLogger() 41 | log_event('testevent', **{'type': 'type_1', 'time': 123456}) 42 | assert len(caplog.records()) == 1 43 | record = caplog.records()[0] 44 | assert 'event=testevent' in record.msg 45 | assert 'type=type_1' in record.msg 46 | assert 'time=123456' in record.msg 47 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27, py35 3 | 4 | [testenv] 5 | setenv = 6 | PYTHONPATH = {toxinidir}:{toxinidir}/django_logutils 7 | commands = py.test 8 | deps = 9 | -r{toxinidir}/requirements/test.txt 10 | --------------------------------------------------------------------------------