apache2+djiango+logging configuration

本文详细介绍了一种在Django项目中实现日志文件自动切割和限定大小的方法,并提供了具体的配置示例。通过这种方式,可以有效避免日志文件过大带来的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

坦白说,这条路上的坑不少,因为一个配置不慎,就会说你的项目跑不起来;因为这个原因,很多人都不敢在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 logging
logger = 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.这个问题我找了许多文章才找到解决方法,希望后人不要再踩坑



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值