• log4j 日志服务器


    //因为暂时没有时间整理,下面的作为草稿先放着

    利用Log4j 创建日志服务器

    在J2EE集群运行模式下,日志的记录是一个重要的问题,如果集群中每一个实例均采用自己的日志记录方式,将会在每一台计算机上均有自己的日志文件,对于日志的查看也是一个问题。
    幸亏我们有Log4J,Log4J中有通过网络的日志服务器

    日志服务器参数的配置

    #文件名socketserver.properties
    #log4j.rootCategory=, A1 #如果需要显示日志界面,可以将本行启用
    log4j.rootLogger=DEBUG,A1,A3

    og4j.category.org.apache.log4j.net=INFO

    log4j.appender.A1=org.apache.log4j.lf5.LF5Appender
    log4j.appender.A1.MaxNumberOfRecords=700

    log4j.appender.A4=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.A4.file=c://log//d.log
    log4j.appender.A4.DatePattern='.'yyyyMMdd
    log4j.appender.A4.layout=org.apache.log4j.PatternLayout
    log4j.appender.A4.layout.ConversionPattern=/n/n[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

    log4j.appender.A3=org.apache.log4j.RollingFileAppender
    log4j.appender.A3.file=c://log//r.log
    log4j.appender.A3.MaxFileSize=1024KB
    log4j.appender.A3.MaxBackupIndex=999
    log4j.appender.A3.layout=org.apache.log4j.PatternLayout
    log4j.appender.A3.layout.ConversionPattern=/n/n[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n


    日志服务器的启动脚本

    @echo off
    Java -cp ./log4j-1.2.8.jar org.apache.log4j.net.SocketServer 8887 socketserver.properties .

    客户端Log4j.properties的配置

    log4j.rootCategory=, A1

    # A1 is set to be a LF5Appender which outputs to a Swing
    # logging console.

    log4j.appender.A1=org.apache.log4j.net.SocketAppender
    log4j.appender.A1.RemoteHost=“日志计算机”
    log4j.appender.A1.Port=8887



    后记
    在进行了以上配置以后,系统中所有的日志均可以到日志计算机c:/log目录下面查看了。

    最*因为*台升级改造做了双机模式,日志的记录就成了一个大问题。以前都是一个应用起一个实例只打印一个日志,现在则是因为一个应用起了两个实例,而这两个实例又分别打印日志,这种情况造成我们查看日志,诊断问题的不便,因为必须把两个实例打的日志都拿到,才是这个应用的全部日志。
    另外*台有多个子系统组成,这些子系统都有自己的日志,并且运行在不同的操作系统和主机上,收集这些日志对运营人员来说也比较困难。
    针对以上两个问题,我们决定在*台中采用日志服务器来做到集中日志管理,*台中所有子系统通过socket方式将日志信息传到日志服务器,再由日志服务器统一记录。这样既避免了一个应用日志不同实例分别打印,也可以将所有子系统日志集中管理,并能够自定义输出路径。
    我们的*台基于J2EE架构实现,故在各应用和各子系统均使用了Log4j,考虑到Log4j提供了SocketAppender可以直接调用,我们决定日志服务器仍然基于Log4j实现。
    Log4j提供了一个简单的基于socket的日志服务器,但直接使用这个服务器不能完全满足我们的需求,首先它自身代码存在问题,需要修改;其次即使修改正确,该服务器也只能按客户端IP配置打印appender,而我们有些子系统是运行在同一主机,直接使用该服务器只能将运行在同一主机上的子系统日志打在一起,不便于分析处理。我们要求按照不同应用输出日志。
    稍经改造,Log4j提供的这个服务器就能较好地提供服务,满足我们的使用要求了。
    Log4j提供的日志服务器由SocketServer.javaSocketNode.java实现,我们需要改造这两个类,以达到我们的目的。
    Log4j提供的SocketServer利用一个Hashtable的变量hierarchyMap保存各个客户端的log4j配置信息,一旦侦听到某个客户端发送请求过来,则立刻New一个SocketNode来处理该请求,该SocketNode的构造参数中有一个是从hierarchyMap中获取的log4j配置信息,SocketNode将根据该配置信息直接输出客户端发送的日志请求。
    改造后的日志服务器, SocketServer仍然利用hierarchyMap保存各个客户端的log4j配置信息,但这次不是基于客户端IP,而是基于应用的,当侦听到某个客户端发送请求过来,则同样New一个SocketNode来处理该请求,hierarchyMap将作为改造后的SocketNode一个构造参数,这样SocketNode自己就能够根据客户端请求内容来决定使用哪个log4j配置信息输出客户端日志请求,这里有个关键就是客户端需要上传信息表明自己是哪个应用。
    分析Log4j源码,我们发现可以为SocketAppender配置一个属性application,而这个属性在服务端是可以获取的,SocketNode读取这个属性并自动选择相应的log4j配置信息来处理。
    修改后的相关代码和配置文件如下:
    //#SocketServer.java

    import java.io.File;

    import java.net.InetAddress;

    import java.net.ServerSocket;

    import java.net.Socket;

    import java.util.Hashtable;



    import org.apache.log4j.Hierarchy;

    import org.apache.log4j.Level;

    import org.apache.log4j.Logger;

    import org.apache.log4j.PropertyConfigurator;

    import org.apache.log4j.spi.RootLogger;



    public class SocketServer {



            static String CLIENT_DIR = "client";

            static String CONFIG_FILE_EXT = ".properties";



            static Logger cat = Logger.getLogger(SocketServer.class);

            static SocketServer server;

            static int port;// key=application, value=hierarchy

            Hashtable<String, Hierarchy> hierarchyMap;

            String dir;



            public static void main(String argv[]) {

                     if (argv.length == 2)

                            init(argv[0], argv[1]);

                    else

                            usage("Wrong number of arguments.");



                    //init("30020", "config");

                    try {

                            cat.info("Listening on port " + port);

                            ServerSocket serverSocket = new ServerSocket(port);

                            while (true) {

                                    cat.info("Waiting to accept a new client.");

                                    Socket socket = serverSocket.accept();

                                    InetAddress inetAddress = socket.getInetAddress();

                                    cat.info("Connected to client at " + inetAddress);

                                    cat.info("Starting new socket node.");

                                    new Thread(new SocketNode(socket, server.hierarchyMap)).start();

                            }

                    } catch (Exception e) {

                            e.printStackTrace();

                    }

            }



            static void usage(String msg) {

                    System.err.println(msg);

                    System.err.println("Usage: java " + SocketServer.class.getName() + " port configFile directory");

                    System.exit(1);

            }



            static void init(String srvPort, String configDir) {

                    try {

                            port = Integer.parseInt(srvPort);

                    } catch (java.lang.NumberFormatException e) {

                            e.printStackTrace();

                            usage("Could not interpret port number [" + srvPort + "].");

                    }



                    PropertyConfigurator.configure(configDir + File.separator + "socketserver.properties");



                    server = new SocketServer(configDir);

            }



            public SocketServer(String configDir) {

                    this.dir = configDir;

                    hierarchyMap = new Hashtable<String, Hierarchy>(11);

                    configureHierarchy();



            }



            // This method assumes that there is no hiearchy for inetAddress

            // yet. It will configure one and return it.

            void configureHierarchy() {

                    File configFile = new File(dir + File.separator + CLIENT_DIR);

                    if (configFile.exists() && configFile.isDirectory()) {

                            String[] clients = configFile.list();

                            for (int i = 0; i < clients.length; i++) {

                                    File client = new File(dir + File.separator + CLIENT_DIR + File.separator + clients[i]);

                                    if (client.isFile()) {

                                            Hierarchy h = new Hierarchy(new RootLogger(Level.DEBUG));

                                            String application = clients[i].substring(0, clients[i].indexOf("."));

                                            cat.info("Locating configuration file for " + application);

                                            hierarchyMap.put(application, h);

                                            new PropertyConfigurator().doConfigure(client.getAbsolutePath(), h);

                                    }

                            }

                    }

            }

    }

    //#SocketNode.java

    import java.io.BufferedInputStream;

    import java.io.IOException;

    import java.io.ObjectInputStream;

    import java.net.Socket;

    import java.util.Hashtable;



    import org.apache.log4j.Hierarchy;

    import org.apache.log4j.Logger;

    import org.apache.log4j.spi.LoggingEvent;



    // Contributors: Moses Hohman <mmhohman@rainbow.uchicago.edu>



    /**

    * Read {@link LoggingEvent} objects sent from a remote client using Sockets

    * (TCP). These logging events are logged according to local policy, as if they

    * were generated locally.

    *

    * <p>

    * For example, the socket node might decide to log events to a local file and

    * also resent them to a second socket node.

    *

    * @author Ceki Gülcü

    *

    * @since 0.8.4

    */


    public class SocketNode implements Runnable {



            Socket socket;

            ObjectInputStream ois;

            Hashtable<String, Hierarchy> hashtable;



            static Logger logger = Logger.getLogger(SocketNode.class);



            public SocketNode(Socket socket, Hashtable<String, Hierarchy> hashtable) {

                    this.socket = socket;

                    this.hashtable = hashtable;

                    try {

                            ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));

                    } catch (Exception e) {

                            logger.error("Could not open ObjectInputStream to " + socket, e);

                    }

            }



            // public

            // void finalize() {

            // System.err.println("-------------------------Finalize called");

            // System.err.flush();

            // }



            public void run() {

                    LoggingEvent event;

                    Logger remoteLogger;



                    try {

                            if (ois != null) {

                                    while (true) {

                                            // read an event from the wire

                                            event = (LoggingEvent) ois.readObject();

                                            Object application = event.getMDC("application");

                                            if (application != null) {

                                                    // get a logger from the hierarchy. The name of the

                                                    // logger

                                                    // is taken to be the name contained in the event.

                                                    remoteLogger = hashtable.get(application).getLogger(event.getLoggerName());



                                                    // logger.info(remoteLogger.getAppender(application.toString()));

                                                    // event.logger = remoteLogger;

                                                    // apply the logger-level filter

                                                    if (remoteLogger != null && event.getLevel().isGreaterOrEqual(remoteLogger.getEffectiveLevel())) {

                                                            // finally log the event as if was generated locally

                                                            remoteLogger.callAppenders(event);

                                                    }



                                            }

                                    }

                            }

                    } catch (java.io.EOFException e) {

                            logger.info("Caught java.io.EOFException closing conneciton.");

                    } catch (java.net.SocketException e) {

                            logger.info("Caught java.net.SocketException closing conneciton.");

                    } catch (IOException e) {

                            logger.info("Caught java.io.IOException: " + e);

                            logger.info("Closing connection.");

                    } catch (Exception e) {

                            logger.error("Unexpected exception. Closing conneciton.", e);

                    } finally {

                            if (ois != null) {

                                    try {

                                            ois.close();

                                    } catch (Exception e) {

                                            logger.info("Could not close connection.", e);

                                    }

                            }

                            if (socket != null) {

                                    try {

                                            socket.close();

                                    } catch (IOException ex) {

                                    }

                            }

                    }

    }

    }
     
    日志服务器参数的配置,文件名必须为socketserver.properties,该配置文件必须置于日志服务器的启动脚本LogServer.bat上层目录下的配置文件夹下,该配置文件夹在LogServer.bat中指定,本文中提到的配置文件夹为config

    #文件名socketserver.properties
    log4j.rootCategory=INFO, STDOUT
     
    log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
    log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
    log4j.appender.STDOUT.layout.ConversionPattern=[%d{yyyy-MM-dd HH/:mm/:ss}][%5p][%5t][%l] %m%n

    日志服务器端各应用的log4j配置文件,必须放在config/client目录下,这里可以部署多个配置文件,日志服务器启动的时候会一次读入所有的配置信息。

    #文件名test.properties
    log4j.rootLogger=info,test
    log4j.category.org.springframework.jdbc=debug,test
    log4j.category.test=debug,test
    log4j.additivity.test=false
    log4j.additivity.org.springframework.jdbc=false
     
    log4j.appender.test=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.test.DatePattern='.'yyyy-MM-dd
    log4j.appender.test.File=${logPath}/test/bmr.log
    log4j.appender.test.Append=true
    log4j.appender.test.Threshold=INFO
    log4j.appender.test.layout=org.apache.log4j.PatternLayout
    log4j.appender.test.layout.ConversionPattern=[%d{yyyy-MM-dd HH/:mm/:ss}][%5p][%5t][%l] %m%n


    日志服务器的启动脚本LogServer.bat

     @echo off
    java -cp ./log4j-1.2.8.jar -DlogPath=D:/LogServer/log *****.SocketServer 30020 config

     
    某个客户端Log4j.properties的配置,注意SocketAppenderapplication属性,要求和服务器端某个应用的log4j配置文件对应。

    log4j.rootCategory=, test
    log4j.appender.test=org.apache.log4j.net.SocketAppender
    log4j.appender.test.RemoteHost=“
    日志计算机
    log4j.appender.test.Port=30020
    log4j.appender.test.application=test

    本文出自 “崔莹峰” 博客,请务必保留此出处http://cuiyingfeng.blog.51cto.com/43841/271817

    1.基本使用
      
      1.1服务器
      
      这个日志服务器的服务器端需要运行:
      
      log4j jar包中的org.apache.log4j.net.SocketServer
      
      加参数 【本地监听端口】【配置文件】【客户端配置文件目录】
      
      第三个参数【配置文件目录】其实指的是针对每个客户端的配置文件,等会详细讲!现在用“.”就可以了.
      
      服务器端的配置文件可以用这个(引自利用Log4j 创建日志服务器 By ?の?):
      
      #文件名socketserver.properties
      #如果需要显示日志界面,可以将本行启用
      #log4j.rootCategory=, A1
      log4j.rootLogger=DEBUG,A3
      log4j.category.org.apache.log4j.net=INFO
      
      log4j.appender.A1=org.apache.log4j.lf5.LF5Appender
      log4j.appender.A1.MaxNumberOfRecords=700
      
      log4j.appender.A4=org.apache.log4j.DailyRollingFileAppender
      log4j.appender.A4.file=server.log
      log4j.appender.A4.DatePattern='.'yyyyMMdd
      log4j.appender.A4.layout=org.apache.log4j.PatternLayout
      log4j.appender.A4.layout.ConversionPattern=/n/n[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
      
      log4j.appender.A3=org.apache.log4j.RollingFileAppender
      log4j.appender.A3.file=server2.log
      log4j.appender.A3.MaxFileSize=1024KB
      log4j.appender.A3.MaxBackupIndex=999
      log4j.appender.A3.layout=org.apache.log4j.PatternLayout
      log4j.appender.A3.layout.ConversionPattern=/n/n[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
      
      其中A1是启动Lf5的log监视终端,A3限制大小的文件,A4是日期滚动文件。
      
      单A3,A4是讲所有客户端的日志都存放到了同一个日志文件中,我觉的这种方法并不好。
      
      1.2客户端
      
      客户端的配置文件是这样的:
      log4j.rootCategory=,SOCKET
      log4j.addivity.org.apache=true
      
      #应用于socket
      log4j.appender.SOCKET=org.apache.log4j.net.SocketAppender
      log4j.appender.SOCKET.RemoteHost=localhost  #服务器的IP地址
      log4j.appender.SOCKET.Port=1978       #服务器的监听端口
      log4j.appender.SOCKET.LocationInfo=true   #这个是什么我不知道
      log4j.appender.SOCKET.layout=org.apache.log4j.PatternLayout
      log4j.appender.SOCKET.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%t%m%n
      
      #A2
      log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
      log4j.appender.A2.file=server.log
      log4j.appender.A2.DatePattern='.'yyyy-MM-dd
      log4j.appender.A2.layout=org.apache.log4j.PatternLayout
      log4j.appender.A2.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
      
      启动服务器端,再运行客户端就可以了!但所有的服务器端/客户端的日志都放到了一个日志文件中!
      
      2.稍微高级点的使用
      
      下面讲如何把各个客户端和服务器端的日志分别放到不同的日志文件中.
      
      这个我在网上找了好久也没有找到!
      
      2.1服务器
      
      服务器的配置文件不用怎么改动,如果你不需要在同一个文件中存放所有日志,可以把配置文件第一行的A3去掉。
      
      但服务器端有个更大的麻烦:代码有问题!问题够大了吧,不知道算不算是个bug(我用的是1.2.11版log4j)。
      
      改吧!
      
      打开log4j目录下的src/java/org/apache/log4j/net/SocketServer.java
      
      在这段中改动(看下面代码第12行)
      
      LoggerRepository configureHierarchy(InetAddress inetAddress) {
      cat.info("Locating configuration file for "+inetAddress);
      // We assume that the toSting method of InetAddress returns is in
      // the format hostname/d1.d2.d3.d4 e.g. torino/192.168.1.1
      String s = inetAddress.toString();
      int i = s.indexOf("/");
      if(i == -1) {
      cat.warn("Could not parse the inetAddress ["+inetAddress+
      "]. Using default hierarchy.");
      return genericHierarchy();
      } else {
      //这个是什么意思,专门取"/"符号吗?明显是错的!闭掉
      //  String key = s.substring(0, i);
      //改为
      String key = s.substring(i+1);
      File configFile = new File(dir, key+CONFIG_FILE_EXT);
      if(configFile.exists()) {
      Hierarchy h = new Hierarchy(new RootLogger((Level) Priority.DEBUG));
      hierarchyMap.put(inetAddress, h);
      
      new PropertyConfigurator().doConfigure(configFile.getAbsolutePath(), h);
      
      return h;
      } else {
      cat.warn("Could not find config file ["+configFile+"].");
      return genericHierarchy();
      }
      }
      }
      
      编译文件!
      
      打开log4j目录下的src/java/org/apache/log4j/net/SocketNode.java
      
      (改这段是因为我用的时候出错!看不出来改不改有什么区别)
      
      改第54行
      
      ois = new ObjectInputStream(
      new BufferedInputStream(socket.getInputStream()));
      
      为
      
      InputStream is = socket.getInputStream();
      if (is != null) {
      ois = new ObjectInputStream(new BufferedInputStream(is));
      }
      
      文件头加 import java.io.InputStream;
      
      编译文件!
      
      现在为每个配置客户端编配置文件,把配置文件放到【客户端配置文件目录】中:
      log4j.rootCategory=,A4
      log4j.appender.A4=org.apache.log4j.DailyRollingFileAppender
      log4j.appender.A4.file=127.0.0.1.log  #为每个客户端取不同的名字
      log4j.appender.A4.DatePattern='.'yyyyMMdd
      log4j.appender.A4.layout=org.apache.log4j.PatternLayout
      log4j.appender.A4.layout.ConversionPattern=/n/n[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
      
      保存文件名为[客户端ip地址].lcf 如192.168.0.126.lcf
      
      2.2 客户端
      
      客户端不用改变,太幸运了!!
      
      ok啦!
      
      启动服务器,启动客户端,现在服务器的日志放到了server.log中,有配置文件的客户端的日志会放到相应的日志文件中,没有配置文件的客户端的日志依然放在server.log中!
      
      SocketServer.java 和 SocketNode.java两个文件可以单独做一个工程,把他们的package去掉就行了!

    通过Socket即时查看远程服务器Log4J日志

    一个项目,因为一个SVF的报表服务器在日本客户那边,在调试程序的时候,需要远程查看Tomcat的后台信息。一开始是将日志写在一个日志文件中,每次需要用ftp远程下载日志文件查看后台的一些调试信息,由于国内和日本之间的网速非常的慢,所以整个调试的过程是非常痛苦的。某一天看了一篇介绍Log4J的文章,发现日志除了文件,后台之类常用Appender,还可以用Socket来传送。

    查了一些资料,写了个远程查看远程服务器Log4J日志的类:

    程序代码 程序代码

    import java.io.EOFException;
    import java.io.IOException;
    import java.io.ObjectInputStream;

    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.SocketException;

    import java.util.Date;

    import org.apache.log4j.PatternLayout;
    import org.apache.log4j.spi.LoggingEvent;

    public class LogView extends Thread {

        private Socket socket;

        private static PatternLayout pl = new PatternLayout(
                "%5p %d{yyyy/MM/dd HH:mm:ss} %m%n");

        public LogView(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            readData();
        }

        protected void readData() {
            ObjectInputStream in = null;
            try {
                in = new ObjectInputStream(socket.getInputStream());
                do {
                    LoggingEvent loggingEvent = (LoggingEvent) in.readObject();
                    System.out.print(pl.format(loggingEvent));
                    String stackTrace[] = loggingEvent.getThrowableStrRep();
                    System.out.print(getFormattedString(stackTrace));
                } while (true);
            } catch (EOFException e) {
            } catch (SocketException s) {
            } catch (Throwable t) {
                t.printStackTrace();
            }
            close(in);
            closeSocket();
            in = null;
            socket = null;
        }

        public String getFormattedString(String stackTrace[]) {
            StringBuffer buffer = new StringBuffer();
            if (getStackTracePresent(stackTrace)) {
                buffer.append("/nThrowable: ").append(stackTrace[0]).append('/n');
                for (int i = 1; i < stackTrace.length; i++)
                    buffer.append(stackTrace[i]).append('/n');

            }
            String formattedString = buffer.toString();
            buffer.setLength(0);
            buffer = null;

            return formattedString;
        }

        public boolean getStackTracePresent(String stackTrace[]) {
            return stackTrace != null;
        }

        protected void close(ObjectInputStream in) {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        protected void closeSocket() {
            if (socket != null)
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        public static void main(String[] args) throws IOException {
            ServerSocket server = new ServerSocket(5001);
            System.out.println("ViewLog start....");
            while (true) {
                LogView logview = new LogView(server.accept());
                logview.start();
            }
        }
    }



    Log4J配置文件中需要添加一个通过socket的日志appender

    程序代码 程序代码
        
    <appender name="socket" class="org.apache.log4j.net.SocketAppender">
        <param name="RemoteHost" value="10.11.2.248" />
        <param name="Port" value="5001" />
        <param name="LocationInfo" value="true" />
    </appender>

    <category name="net.lurenjia.nunu.test">
        <priority value="DEBUG" />
        <appender-ref ref="socket" />
    </category>

     

     

     

     

     

    *来要做日志服务器,以便集中管理,windows,java,linux的日志,在网上找了很久,都是些零零散散关于log4j日志和syslog-ng的,基本上没有直接能把log4j的日志发送给远程syslog-ng来管理的,在这里只把个人的一个成功办法记下来,方便有需要的兄弟,也希望能抛金引玉,XD们有更多的好建议
        在这里如何安装程序就不讲了,论坛里面有,再不用google找也可以找到的。

    ----------
    1.安装syslog-ng
    # vi /usr/local/syslog-ng/etc/syslog-ng.conf
    options {
            use_fqdn(yes);
            chain_hostnames(off);
            keep_hostname(off);
            sync(0);
            # The default action of syslog-ng 1.6.0 is to log a STATS line
            # to the file every 10 minutes.  That's pretty ugly after a while.
            # Change it to every 12 hours so you get a nice daily update of
            # how many messages syslog-ng missed (0).
            stats(43200);
            create_dirs(yes);
    };
    source s_internal { internal(); };
    destination d_syslognglog { file("/var/log/syslog-ng.log"); };
    log { source(s_internal); destination(d_syslognglog); };
    source s_sys { file ("/proc/kmsg" log_prefix("kernel: ")); unix-stream ("/dev/log"); internal(); };
    destination d_cons { file("/dev/console"); };
    destination d_mesg { file("/var/log/messages"); };
    destination d_auth { file("/var/log/secure"); };
    destination d_mail { file("/var/log/maillog"); };
    destination d_spol { file("/var/log/spooler"); };
    destination d_boot { file("/var/log/boot.log"); };
    destination d_cron { file("/var/log/cron"); };
    destination d_rsync { file("/var/log/rsync"); };
    destination d_mlal { usertty("*"); };
    filter f_filter1     { facility(kern); };
    filter f_filter2     { level(info) and
                         not (facility(mail)
                            or facility(authpriv) or facility(cron)); };
    filter f_filter3     { facility(authpriv); };
    filter f_filter4     { facility(mail); };
    filter f_filter5     { level(emerg); };
    filter f_filter6     { facility(uucp) or
                         (facility(news) and level(crit)); };
    filter f_filter7     { facility(local7); };
    filter f_filter8     { facility(cron); };
    filter f_filter9     { facility(daemon); };
    filter f_filter10     { facility(local6); };
    #log { source(s_sys); filter(f_filter1); destination(d_cons); };
    log { source(s_sys); filter(f_filter2); destination(d_mesg); };
    log { source(s_sys); filter(f_filter3); destination(d_auth); };
    log { source(s_sys); filter(f_filter4); destination(d_mail); };
    log { source(s_sys); filter(f_filter5); destination(d_mlal); };
    log { source(s_sys); filter(f_filter6); destination(d_spol); };
    log { source(s_sys); filter(f_filter7); destination(d_boot); };
    log { source(s_sys); filter(f_filter8); destination(d_cron); };
    # Remote logging
    source s_remote {
            udp(ip(0.0.0.0) port(514));
    };

    destination r_mesg { file("/var/log/syslog-ng/$YEAR$MONTH$DAY/$HOST/messages" owner("root") group("root") perm(0640) dir_perm(0750) create_dirs(yes)); };
    destination r_auth { file("/var/log/syslog-ng/$YEAR$MONTH$DAY/$HOST/secure" owner("root") group("root") perm(0640) dir_perm(0750) create_dirs(yes)); };
    destination r_mail { file("/var/log/syslog-ng/$YEAR$MONTH$DAY/$HOST/maillog" owner("root") group("root") perm(0640) dir_perm(0750) create_dirs(yes)); };
    destination r_spol { file("/var/log/syslog-ng/$YEAR$MONTH$DAY/$HOST/spooler" owner("root") group("root") perm(0640) dir_perm(0750) create_dirs(yes)); };
    destination r_boot { file("/var/log/syslog-ng/$YEAR$MONTH$DAY/$HOST/boot.log" owner("root") group("root") perm(0640) dir_perm(0750) create_dirs(yes)); };
    destination r_cron { file("/var/log/syslog-ng/$YEAR$MONTH$DAY/$HOST/cron" owner("root") group("root") perm(0640) dir_perm(0750) create_dirs(yes)); };
    destination r_daemon { file("/var/log/syslog-ng/$YEAR$MONTH$DAY/$HOST/daemon" owner("root") group("root") perm(0640) dir_perm(0750) create_dirs(yes)); };
    destination r_local6 { file("/var/log/syslog-ng/$YEAR$MONTH$DAY/network/messages" owner("root") group("root") perm(0640) dir_perm(0750) create_dirs(yes)); };
    #destination d_separatedbyhosts {
    #       file("/var/log/syslog-ng/$HOST/messages" owner("root") group("root") perm(0640) dir_perm(0750) create_dirs(yes));
    #};
    #log { source(s_remote); destination(d_separatedbyhosts); };
    log { source(s_remote); filter(f_filter2); destination(r_mesg); };
    log { source(s_remote); filter(f_filter3); destination(r_auth); };
    log { source(s_remote); filter(f_filter4); destination(r_mail); };
    log { source(s_remote); filter(f_filter6); destination(r_spol); };
    log { source(s_remote); filter(f_filter7); destination(r_boot); };
    log { source(s_remote); filter(f_filter8); destination(r_cron); };
    log { source(s_remote); filter(f_filter9); destination(r_daemon); };
    log { source(s_remote); filter(f_filter10); destination(r_local6); };

    # syslog-ng conf file for use with phpsyslog-ng
    #source src {
    #  unix-stream("/dev/log" max-connections(256));
    #  internal();
    #  file("/proc/kmsg");
    #  tcp();
    #  udp();
    #};
    #
    #log {
    #  source(src);
    #  destination(d_mysql);
    #};
    #
    #destination d_mysql {
    #  program("/usr/bin/mysql --user=root --password=  syslog < /var/log/mysql.pipe");
    #  pipe("/var/log/mysql.pipe" template("INSERT INTO logs (host, facility, priority, level, tag, datetime, program, msg) VALUES ( '$HOST', '$FACILITY', '$PRIORITY', '$LEVEL', '$TAG', '$YEAR-$MONTH-$DAY $HOUR:$MIN:$SEC','$PROGRAM', '$MSG' );/n") template-escape(yes));
    #};

    把syslog-ng增加到开机启动
    #echo "/usr/local/syslog-ng/sbin/syslog-ng" >> /etc/rc.local

    2.JAVA日志

    安装tomcat和java环境请看本人另外的文章。这里主要讲log4j的相关配置,把日志发送给远程syslog-ng服务器

    在tomcat的一个应用工程里面vi /.../WEB-INF/classes/log4j.properties
    ################ write to the file##################
    log4j.rootLogger=info,debug,warn,syslog,A1
    log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.A1.file=/var/log/messages
    #log4j.appender.A1.DatePattern=yyyy-MM-dd'.log'
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss, SSS}[%c]-[%p] %m%n
    ######################## write to the syslog ######################
    # Appender to syslog
    #log4j.rootCategory=INFO,DEBUG, CONSOLE, FILE, syslog
    log4j.appender.syslog=org.apache.log4j.net.SyslogAppender
    #log4j.appender.syslog.SyslogHost=192.168.76.100 (日志服务器的IP地址)      
    log4j.appender.syslog.SyslogHost=127.0.0.1
    log4j.appender.syslog.Port=514
    log4j.appender.syslog.Facility=local5        
    log4j.appender.syslog.layout=org.apache.log4j.PatternLayout        
    log4j.appender.syslog.layout.ConversionPattern=%p: %c{2} - %m%n

    修改本地syslog

    vi /etc/syslog.conf
    local5.*                                         @192.168.76.100(日志服务器的IP地址)

    3.windows日志
    windows日志不支持syslog格式
    下载地址为:https://engineering.purdue.edu/E ... uments/UNIX/evtsys/
    解压后是两个文件evtsys.dll和evtsys.exe
    把这两个文件拷贝到 c:/windows/system32目录下。
    打开Windows命令提示符(开始->运行 输入CMD)
    C:/>evtsys –i –h 192.168.76.100   #(日志服务器的IP地址)
    -i 表示安装成系统服务
    -h 指定log服务器的IP地址
    如果要卸载evtsys,则:
    net stop evtsys
    evtsys -u
    启动该服务:
    C:/>net start evtsys

    配置完成

    4.syslog日志
        编辑下面文件,加入下列语句就可以了。
       #vi /etc/syslog.conf
    *.*     @remotehost

    #########

  • 相关阅读:
    poj 2349 Arctic Network
    hdu 1596 find the safest road
    Codeforces 768B. Code For 1
    Codeforces 448C. Painting Fence
    Problem D. Ice Cream Tower(2016 China-Final)
    poj 2785 4 Values whose Sum is 0
    Codeforces 797C. Minimal string
    Codeforces 264A. Escape from Stones
    乌龟棋(noip2010)
    noip2018模拟题(类背包+贪心)
  • 原文地址:https://www.cnblogs.com/cuker919/p/4878606.html
Copyright © 2020-2023  润新知