apache2+djiango+logging configuration

来源:互联网 发布:网络运营学校 编辑:程序博客网 时间:2024/06/16 04:24

坦白说,这条路上的坑不少,因为一个配置不慎,就会说你的项目跑不起来;因为这个原因,很多人都不敢在djiango的settings.py里进行logging配置了,而是为了省事,直接看/var/www/apache2下的log.但这个log没有配置成自动给你切割文件及限定文件大小,这对于我来说是不能接受的,用东东,就要用好的。不啰嗦,上方案。

项目所在目录/home/page/mysite


1.修改djiango的settings.py文件,加上logging配置.

# Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/1.6/howto/static-files/MEDIA_URL = '/media/'STATIC_URL = '/static/'STATIC_ROOT = os.path.join(BASE_DIR,'static')STATICFILES_DIRS = [    os.path.join(BASE_DIR, "blog/static"),]STATICFILES_FINDERS = (    'django.contrib.staticfiles.finders.FileSystemFinder',    'django.contrib.staticfiles.finders.AppDirectoriesFinder',#    'django.contrib.staticfiles.finders.DefaultStorageFinder',)SESSION_ENGINE = 'django.contrib.sessions.backends.file'LOGGING = {      "version": 1,      "disable_existing_loggers": False,    "formatters": {          "simple": {              "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"          }      },        "handlers": {          "console": {              "class": "logging.StreamHandler",              "level": "DEBUG",              "formatter": "simple",              "stream": "ext://sys.stdout"          },            "info_file_handler": {              "class": "logging.handlers.RotatingFileHandler",              "level": "INFO",              "formatter": "simple",              "filename": os.path.join(STATIC_ROOT+'/logs/','info.log'),              "maxBytes": 10485760,              "backupCount": 20,              "encoding": "utf8"          },            "error_file_handler": {              "class": "logging.handlers.RotatingFileHandler",              "level": "ERROR",              "formatter": "simple",              "filename": os.path.join(STATIC_ROOT+'/logs/','error.log'),              "maxBytes": 10485760,              "backupCount": 20,              "encoding": "utf8"          }      },        "loggers": {          "my_module": {              "level": "INFO",              "handlers": ["info_file_handler"],              "propagate": "no"          }    },        "root": {          "level": "INFO",          "handlers": ["console"]      }  }  

2.在/home/page/mysite下创建目录/static/log



3.在python文件里如何使用logging.

import logginglogger = logging.getLogger('my_module')# Create your views here.def index(request):    #blog_list = BlogsPost.objects.all()    blog_list = [{"title":"111111111","timestamp":"kkkkkkkk","body":"jjjjjjjjjjj"},{"title":"222222222222","timestamp":"kkkkkkkk","body":"jjjjjjjjjjj"}]    return render_to_response('index.html',{'blog_list':blog_list})@api_view(['GET', 'POST'])def hello(request):    blog_list = BlogsPost.objects.all()    cur = connection.cursor()    cur.execute("select * from blog_blogspost;")    rows = cur.fetchall()        connection.commit()    cur.close()        logger.info('Start reading database')    # read database here        records = {'john': 55, 'tom': 66}    logger.debug('Records: %s', records)    logger.info('Updating records ...')    # update records here        logger.info('Finish updating records')    if(rows):message=rows[0]    else:message = {    "count": 4,    "next": "http://localhost:8000/api/entries/?limit=2&offset=2",    "previous": None,    "results": [{    "id": 1,    "title": "Hello, Django REST Framework!!",    "body": "Hello!",    "created_at": "2015-12-12T11:55:22.310203Z",    "status": "draft",    "author": 1},{    "id": 2,    "title": "The Zen of Python",    "body": "The Zen of Python, by Tim Peters\r\n\r\nBeautiful is better than ugly.\r\nExplicit is better than implicit.\r\nSimple is better than complex.\r\nComplex is better than complicated.\r\nFlat is better than nested.\r\nSparse is better than dense.\r\nReadability counts.\r\nSpecial cases aren't special enough to break the rules.\r\nAlthough practicality beats purity.\r\nErrors should never pass silently.\r\nUnless explicitly silenced.\r\nIn the face of ambiguity, refuse the temptation to guess.\r\nThere should be one-- and preferably only one --obvious way to do it.\r\nAlthough that way may not be obvious at first unless you're Dutch.\r\nNow is better than never.\r\nAlthough never is often better than *right* now.\r\nIf the implementation is hard to explain, it's a bad idea.\r\nIf the implementation is easy to explain, it may be a good idea.\r\nNamespaces are one honking great idea -- let's do more of those!",    "created_at": "2015-12-12T11:56:32.854278Z",    "status": "draft",    "author": 2}    ]}    return Response(message)

4.在/home/page/mysite/static/logs查看error.log及info.log

5.在/var/log/apache2里查看error.log

可以看到两处log都记录了


关键点在下面这句

 "disable_existing_loggers": False,

另外会有坑的是如果你在python方法里用了print语句,在/var/log/apache2/error.log文件里就会出现wgi_err.这个问题我找了许多文章才找到解决方法,希望后人不要再踩坑



阅读全文
0 0
原创粉丝点击