热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

LOG收集系统(一):原日志至收集

Date:20140207Auth:Jin设置一个LOG收集系统1.收集原生(不解析,不压缩)的业务日志和WEB日志(NGI

Date: 20140207
Auth: Jin

设置一个LOG收集系统
1. 收集原生(不解析,不压缩)的业务日志和WEB日志(NGINX,PHP)
2. 提供给开发,测试直接阅读和下载

需求分析
原生日志,所以不需要其他程序介入,需要收集和阅读下载,具体分析开发测试人员拿到日子自行处理
1、收集可以通过FTP采集
2、阅读和下载可以通过WEB形式
3、收集周期可以通过crontab控制脚本实现, 初步设置为每小时
4、核心是收集日子的脚本,考虑到扩展和重复使用,我使用python编写d

步骤
一、搭建FTP服务器

1.install

yum install pure-ftpd

2.config

mkdir /data/ftproot/logs

chown webroot.webroot /data/ftproot/logs

vim /etc/pure-ftpd/pure-ftpd.conf

注意流量参数

Bind 10.0.0.221,21
ChrootEveryone yes
BrokenClientsCompatibility yes
Daemonize yes
MaxClientsPerIP
20
VerboseLog yes
DisplayDotFiles no
AnonymousOnly no
NoAnonymous yes
SyslogFacility none
DontResolve yes
MaxIdleTime
15
LimitRecursion
10000 8
AnonymousCanCreateDirs no
MaxLoad
4
PassivePortRange
45000 50000
#AnonymousRatio
1 10
#UserRatio
1 10
AntiWarez yes
#AnonymousBandwidth
200
UserBandwidth
8
Umask
133:02
MinUID
100
AllowUserFXP no
AllowAnonymousFXP no
ProhibitDotFilesWrite no
ProhibitDotFilesRead no
AutoRename yes
AnonymousCantUpload yes
AltLog clf:/var/log/pureftpd.log
PureDB /etc/pure-ftpd/pureftpd.pdb
MaxDiskUsage
99
CreateHomeDir no
CustomerProof yes

View Code

 3.start ftp seriver

/etc/init.d/pure-ftpd restart
Stopping pure-ftpd: [ OK ]
Starting pure-ftpd: [ OK ]

chkconfig pure-ftpd on

4.add account

# pure-pw useradd logsftp -u 9999 -g 9999 -d /data/ftproot/logs
Password:
Enter it again:

# pure-pw mkdb
# /etc/init.d/pure-ftpd restart
Stopping pure-ftpd: [ OK ]
Starting pure-ftpd: [ OK ]

5.test

on opensuse desktop test

# zypper install lftp

lftp 10.0.0.221
lftp 10.0.0.221:~> user logsftp
Password:
lftp logsftp@10.0.0.221:~> ls
ls: Login failed: 530 ��֤ʧ�ܣ���Ǹ
lftp logsftp@10.0.0.221:~>

二、搭建WEB服务器
DOCMENTROOT为

server {listen 80;
server_name logs.test.com;
root /data/ftproot/logs/;
location / {index index.htm index.html;
autoindex on;
autoindex_localtime on;
auth_basic "logs access";
auth_basic_user_file log-auth.conf;
error_log off;
access_log /var/log/nginx/log.test.com-access.log;
#access_log off;
}}

注意点:

autoindex_localtime on;
参考:http://blog.chinaunix.net/uid-26719405-id-3508444.html
autoindex_localtime on;
默认为off,显示的文件时间为GMT时间。
改为on后,显示的文件时间为文件的服务器时间

三、代码编写

无LOG版本

加入计划任务

5 * * * * /home/gbin/logcollect.py >> /home/gbin/logcollect.log 2>&1

计划任务报错 登录用户问题

删除userName = os.getlogin()

  • 配置文件logcollect.ini

[global]
ip
= 127.0.0.1
username
= logsftp
password
= pwd
mode
= 0[applogs]
dms-log
= /home/dms/logs/service.log
store-logdir
= /home/store/logs/
stock-logdir
= /home/stock/logs/[weblogs]
nginxlog
= /var/log/nginx.log
phplog
= /var/log/php-fpm/php-fpm.log

  • 函数和对象:gbopt.py

    #!/usr/bin/env python
    #
    coding=utf8
    '''
    Created on 2014-03-05 @author: Jin
    ''' __version__ = "0.0.1#date:2014-03-05" __all__ = ['readConfig', 'ftpPutGb', 'OptFile' ] import os
    import sys
    import ConfigParser
    import ftplib
    import time
    import socket
    from ftplib import FTP
    from time import strftime as printtime
    from time import sleep as waitprogName = 'logcollect'
    userName
    = os.getlogin()
    hostName
    = socket.gethostname()
    pwdDir
    = os.getcwd()
    workDir
    = os.path.dirname(sys.argv[0])configFile = progName+'.ini'
    todayDate
    = time.strftime("%Y%m%d", time.localtime())if workDir == '' or workDir == '.':progDir = pwdDir
    elif workDir.startswith('/'):progDir = workDir
    elif workDir.startswith('./'):progDir = pwdDir+workDir.lstrip('.')
    else:progDir = pwdDir+'/'+workDirconfPath = progDir+'/'+configFile
    logPath
    &#61; progDir&#43;&#39;/&#39;&#43;progName&#43;&#39;.log&#39;def readConfig(filename&#61;&#39;&#39;,section&#61;&#39;&#39;):&#39;&#39;&#39;read ini config return dict&#39;&#39;&#39;Call &#61; &#39;Call &#39;&#43;sys._getframe().f_code.co_nameif not os.path.isfile(filename):print "%s: Error, File %s is not exists,Please check it!" % (Call,filename)sys.exit(10)else:try:Config &#61; ConfigParser.ConfigParser()Config.read(filename)sections &#61; Config.sections()configDict &#61; {}for conf in Config.items(section):ckey &#61; conf[0]cvalue &#61; conf[1]configDict[ckey] &#61; cvalueexcept ConfigParser.ParsingError,e:print "%s: Read<%s> Section<%s> Parsing Error with reason<%s>!" % (Call,filename,section,&#39;&#39;.join( repr(e).split(&#39;\n&#39;)))sys.exit(11)except Exception, e:print "%s: Read<%s> Section<%s> Exception error with reason<%s>!" % (Call,filename,section,&#39;&#39;.join( repr(e).split(&#39;\n&#39;)))sys.exit(12)else:return configDictdef ftpPutGb(filename,inittime,server&#61;None,username&#61;None,password&#61;None,localdir&#61;None,remotedir&#61;&#39;testdir&#39;,debuglevel&#61;0,model&#61;1,retrytime&#61;10,timeout&#61;120):"""Put file to FTP server,use local pathexitcode introduce: timeout | 99connect failed | 21user or passwd error | 22create dir fails | 23change dir fails | 24read file fails | 25transfer file fails | 26any ftp transfer fails | 27server or username or password not exist | 28call ftpPutGb(&#39;/home/jin/code/python/tt.ini&#39;,&#39;127.0.0.1&#39;,&#39;logsftp&#39;,&#39;passwd&#39;,remotedir&#61;&#39;testdir1/testdir2/testdir3&#39;,model&#61;0)"""Call &#61; &#39;Call &#39;&#43;sys._getframe().f_code.co_nameif not os.path.isfile(filename):print "Notice: %s is not exists!" % filenamereturn Falseif not localdir:localdir&#61;os.path.dirname(filename)filename&#61;os.path.basename(filename)uploadfile&#61;&#39;STOR &#39;&#43;filenameftp&#61;FTP()bufsize&#61;1024os.chdir(localdir)ftp.set_debuglevel(debuglevel)remotedirList&#61;remotedir.split(&#39;/&#39;)appName&#61;remotedirList[0]machineName&#61;remotedirList[1]dayName&#61;remotedirList[2]if server and username and password:print printtime(&#39;%Y-%m-%d %H:%M:%S&#39;),"Notice: FTPuser(%s) Put %s to FTP(%s:/%s) Begin." % (username,filename,server,remotedir)try:ftp.connect(server)except socket.error:waittime&#61;inittimewait(retrytime)waittime&#43;&#61;retrytimeif waittime&#61;&#61;timeout:print "%s: Put %s to FTP(%s) timeout(%s),exit!" % (Call,filename,server,timeout)sys.exit(20)print "Notice: Retry Put %s to FTP(%s) again after %s s" % (filename,server,retrytime)ftpPutGb(filename,waittime,server,username,password,localdir,remotedir,debuglevel,model,retrytime,timeout)except ftplib.error_perm,e:print "Error: Connect to FTP(%s) failed with<%s>" % (server,e)sys.exit(21)else:try:ftp.login(username,password)ftp.set_pasv(model)except ftplib.error_perm,e:print "Error: User(%s) Login FTP(%s) failed with<%s>" % (username,server,e)sys.exit(22)else:try:try:ftp.mkd(appName)except ftplib.error_perm,e:passfinally:ftp.cwd(appName)try:ftp.mkd(machineName)except ftplib.error_perm,e:passfinally:ftp.cwd(machineName)try:ftp.mkd(dayName)except ftplib.error_perm,e:passfinally:ftp.cwd(dayName)try:file_handler &#61; open(filename,&#39;rb&#39;)except ftplib.error_perm,e:print "Error: User(%s) on FTP(%s) Open file(%s) failed with %s!" % (username,server,filename,e)sys.exit(25)else:try:ftp.storbinary(uploadfile,file_handler,bufsize)except ftplib.error_perm,e:print "Error: User(%s) on FTP(%s) storbinary file(%s) failed with %s!" % (username,server,filename,e)sys.exit(26)except Exception, e:print "Error: User(%s) Put file(%s) to FTP(%s:%s) failed exit with %s!" % (username,filename,server,remotedir,e)sys.exit(27)else:print printtime(&#39;%Y-%m-%d %H:%M:%S&#39;),"Notice: FTPuser(%s) Put %s to FTP(%s:/%s) successful." % (username,filename,server,remotedir)return Truefinally:ftp.set_debuglevel(0)ftp.close()else:print "Error: server(%s) or username(%s) or password(%s) is not exist!" % (server,username,password)sys.exit(28)class OptFile(file):&#39;&#39;&#39;log file object&#39;&#39;&#39;def __init__(self,path,remotedir):self.filePath &#61; pathself.remotedir &#61; remotedirglobalDict &#61; readConfig(confPath,&#39;global&#39;)self.ftpIp &#61; globalDict[&#39;ip&#39;]self.ftpUser &#61; globalDict[&#39;username&#39;]self.ftpPass &#61; globalDict[&#39;password&#39;]self.ftpMode &#61; globalDict[&#39;mode&#39;]file.__init__def put(self):ftpPutGb(self.filePath,0,self.ftpIp,self.ftpUser,self.ftpPass,remotedir&#61;self.remotedir,model&#61;self.ftpMode)def main():pass
    if __name__ &#61;&#61; &#39;__main__&#39;:main()

     

  • 调用脚本&#xff1a;logcollect.py

#!/usr/bin/env python
#
coding&#61;utf8
&#39;&#39;&#39;
Created on 2014-03-05&#64;author: Jin
&#39;&#39;&#39;
import os
import sys
import gboptdef collectLogs(logtype):applogsDict&#61;gbopt.readConfig(gbopt.confPath,logtype)for l in applogsDict:appName&#61;l.split(&#39;-&#39;)[0]hostName&#61;gbopt.hostNamedayName&#61;gbopt.todayDateremoteDir&#61;appName&#43;&#39;/&#39;&#43;hostName&#43;&#39;/&#39;&#43;dayNameif l.endswith(&#39;dir&#39;):locallogPath&#61;applogsDict[l]&#43;gbopt.todayDate&#43;&#39;.log&#39;else:locallogPath&#61;applogsDict[l]logfile&#61;gbopt.OptFile(locallogPath,remoteDir)logfile.put()def main():for i in [&#39;applogs&#39;,&#39;weblogs&#39;]:collectLogs(i)if __name__ &#61;&#61; &#39;__main__&#39;:main()


转:https://www.cnblogs.com/diege/p/3539194.html



推荐阅读
  • 本文介绍了通过ABAP开发往外网发邮件的需求,并提供了配置和代码整理的资料。其中包括了配置SAP邮件服务器的步骤和ABAP写发送邮件代码的过程。通过RZ10配置参数和icm/server_port_1的设定,可以实现向Sap User和外部邮件发送邮件的功能。希望对需要的开发人员有帮助。摘要长度:184字。 ... [详细]
  • Linux如何安装Mongodb的详细步骤和注意事项
    本文介绍了Linux如何安装Mongodb的详细步骤和注意事项,同时介绍了Mongodb的特点和优势。Mongodb是一个开源的数据库,适用于各种规模的企业和各类应用程序。它具有灵活的数据模式和高性能的数据读写操作,能够提高企业的敏捷性和可扩展性。文章还提供了Mongodb的下载安装包地址。 ... [详细]
  • 本文介绍了在Linux下安装和配置Kafka的方法,包括安装JDK、下载和解压Kafka、配置Kafka的参数,以及配置Kafka的日志目录、服务器IP和日志存放路径等。同时还提供了单机配置部署的方法和zookeeper地址和端口的配置。通过实操成功的案例,帮助读者快速完成Kafka的安装和配置。 ... [详细]
  • 解决nginx启动报错epoll_wait() reported that client prematurely closed connection的方法
    本文介绍了解决nginx启动报错epoll_wait() reported that client prematurely closed connection的方法,包括检查location配置是否正确、pass_proxy是否需要加“/”等。同时,还介绍了修改nginx的error.log日志级别为debug,以便查看详细日志信息。 ... [详细]
  • mac php错误日志配置方法及错误级别修改
    本文介绍了在mac环境下配置php错误日志的方法,包括修改php.ini文件和httpd.conf文件的操作步骤。同时还介绍了如何修改错误级别,以及相应的错误级别参考链接。 ... [详细]
  • CEPH LIO iSCSI Gateway及其使用参考文档
    本文介绍了CEPH LIO iSCSI Gateway以及使用该网关的参考文档,包括Ceph Block Device、CEPH ISCSI GATEWAY、USING AN ISCSI GATEWAY等。同时提供了多个参考链接,详细介绍了CEPH LIO iSCSI Gateway的配置和使用方法。 ... [详细]
  • 移动端常用单位——rem的使用方法和注意事项
    本文介绍了移动端常用的单位rem的使用方法和注意事项,包括px、%、em、vw、vh等其他常用单位的比较。同时还介绍了如何通过JS获取视口宽度并动态调整rem的值,以适应不同设备的屏幕大小。此外,还提到了rem目前在移动端的主流地位。 ... [详细]
  • 本文介绍了关系型数据库和NoSQL数据库的概念和特点,列举了主流的关系型数据库和NoSQL数据库,同时描述了它们在新闻、电商抢购信息和微博热点信息等场景中的应用。此外,还提供了MySQL配置文件的相关内容。 ... [详细]
  • PHP组合工具以及开发所需的工具
    本文介绍了PHP开发中常用的组合工具和开发所需的工具。对于数据分析软件,包括Excel、hihidata、SPSS、SAS、MARLAB、Eview以及各种BI与报表工具等。同时还介绍了PHP开发所需的PHP MySQL Apache集成环境,包括推荐的AppServ等版本。 ... [详细]
  • 本文介绍了如何使用MATLAB调用摄像头进行人脸检测和识别。首先需要安装扩展工具,并下载安装OS Generic Video Interface。然后使用MATLAB的机器视觉工具箱中的VJ算法进行人脸检测,可以直接调用CascadeObjectDetector函数进行检测。同时还介绍了如何调用摄像头进行人脸识别,并对每一帧图像进行识别。最后,给出了一些相关的参考资料和实例。 ... [详细]
  • Linux一键安装web环境全攻略
    摘自阿里云服务器官网,此处一键安装包下载:点此下载安装须知1、此安装包可在阿里云所有Linux系统上部署安装,此安装包包含的软件及版本为& ... [详细]
  • 三小时掌握计算机网络基础(通俗易懂)
    目录1.网络层次划分2.OSI七层网络模型3.IP地址4.子网掩码及网络划分5.ARPRARP协议6.路由选择协议7.TCPIP协议8.UDP协议 9.DNS协议 ... [详细]
  • 如何在HTML中获取鼠标的当前位置
    本文介绍了在HTML中获取鼠标当前位置的三种方法,分别是相对于屏幕的位置、相对于窗口的位置以及考虑了页面滚动因素的位置。通过这些方法可以准确获取鼠标的坐标信息。 ... [详细]
  • 在做以下实验时需先做的操作为:(1)打开两个虚拟机(desktop和server)并更改他们的ipÿ ... [详细]
  • 开发笔记:Python脚本优化Zabbix多行日志监控
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Python脚本优化-----Zabbix多行日志监控相关的知识,希望对你有一定的参考价值。通过使用z ... [详细]
author-avatar
restVerify
这个人,怎么说呢,有上进,有头脑
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有