001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package chapters.appenders.socket;
015
016import java.io.BufferedReader;
017import java.io.InputStreamReader;
018
019import ch.qos.logback.core.util.Duration;
020import org.slf4j.LoggerFactory;
021
022import ch.qos.logback.classic.Logger;
023import ch.qos.logback.classic.LoggerContext;
024import ch.qos.logback.classic.net.SocketAppender;
025
026/**
027 * This application uses a SocketAppender that log messages to a
028 * server on a host and port specified by the user. It waits for the
029 * user to type a message which will be sent to the server.
030 * */
031public class SocketClient1 {
032    static void usage(String msg) {
033        System.err.println(msg);
034        System.err.println("Usage: java " + SocketClient1.class.getName() + " hostname port\n" + "   hostname the name of the remote log server\n"
035                        + "   port (integer) the port number of the server\n");
036        System.exit(1);
037    }
038
039    static public void main(String[] args) throws Exception {
040        if (args.length != 2) {
041            usage("Wrong number of arguments.");
042        }
043
044        String hostName = args[0];
045        int port = Integer.parseInt(args[1]);
046
047        // Create a SocketAppender connected to hostname:port with a
048        // reconnection delay of 10000 seconds.
049        SocketAppender socketAppender = new SocketAppender();
050        socketAppender.setRemoteHost(hostName);
051        socketAppender.setPort(port);
052        socketAppender.setReconnectionDelay(new Duration(10000));
053        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
054        socketAppender.setContext(lc);
055
056        // SocketAppender options become active only after the execution
057        // of the next statement.
058        socketAppender.start();
059
060        Logger logger = (Logger) LoggerFactory.getLogger(SocketClient1.class);
061        logger.addAppender(socketAppender);
062
063        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
064
065        while (true) {
066            System.out.println("Type a message to send to log server at " + hostName + ":" + port + ". Type 'q' to quit.");
067
068            String s = reader.readLine();
069
070            if (s.equals("q")) {
071                break;
072            } else {
073                logger.debug(s);
074            }
075        }
076    }
077}