⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 commonlogger.java

📁 很棒的web服务器源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    /**     * It actually does multiple things, check when to rotate log files     * and also dumps the formatted date string to a stringbuffer     * it is dirty but hopefully faster than the previous version of the logger     */    protected synchronized void dateCache(long date, StringBuffer sb) {	if (cal == null) {	    TimeZone tz = TimeZone.getTimeZone("UTC");	    cal = Calendar.getInstance(tz);	}	long ldate;	// should we use the request date or just log the 	// end of the request?	if (date < 0) {	    ldate = System.currentTimeMillis();	} else {	    ldate = date;	}	Date now = new Date(ldate);	cal.setTime(now);	if ((ldate > datestamp + 3600000) || (datestamp == -1)) {	    datestamp = ldate % 3600000;	    if (hour == -1) {		hour = cal.get(Calendar.HOUR_OF_DAY);	    } else {		int nhour = cal.get(Calendar.HOUR_OF_DAY);		if (nhour != hour) {		    hour = nhour;		    TimeZone tz = TimeZone.getTimeZone("UTC");		    cal = Calendar.getInstance(tz);		    cal.setTime(now);		}	    }	    if (rotateLevel > 0) {		checkLogFile(now);	    }	    int day = cal.get(Calendar.DAY_OF_MONTH);	    	    if (day < 10) {		datecache[0] = '0';		datecache[1] = (char)('0' + day);	    } else {		datecache[0] = (char)('0' + day / 10);		datecache[1] = (char)('0' + day % 10);	    }	    monthnames[cal.get(Calendar.MONTH)].getChars(0,3,datecache,3);	    int year = cal.get(Calendar.YEAR);	    datecache[10] = (char)('0' + year % 10);	    year = year / 10;	    datecache[9] = (char)('0' + year % 10);	    year = year / 10;	    datecache[8] = (char)('0' + year % 10);	    year = year / 10;	    datecache[7] = (char)('0' + year);	    if (hour < 10) {		datecache[12] = '0';		datecache[13] = (char)('0' + hour);	    } else {		datecache[12] = (char)('0' + hour / 10);		datecache[13] = (char)('0' + hour % 10);	    }	}	int minutes = cal.get(Calendar.MINUTE);	if (minutes < 10) {	    datecache[15] = '0';	    datecache[16] = (char)('0' + minutes);	} else {	    datecache[15] = (char)('0' + minutes / 10);	    datecache[16] = (char)('0' + minutes % 10);	    	}	int seconds = cal.get(Calendar.SECOND);	if (seconds < 10) {	    datecache[18] = '0';	    datecache[19] = (char)('0' + seconds);	} else {	    datecache[18] = (char)('0' + seconds / 10);	    datecache[19] = (char)('0' + seconds % 10);	    	}	sb.append(datecache);    }	    	    /**     * Log the given HTTP transaction.     * This is shamelessly slow.     */    public void log (Request request, Reply reply, int nbytes, long duration) {	Client client = request.getClient() ;	long   date   = reply.getDate();	String user = (String) request.getState(AuthFilter.STATE_AUTHUSER);	URL urlst = (URL) request.getState(Request.ORIG_URL_STATE);	String requrl;	if (urlst == null) {	    URL u = request.getURL();	    if (u == null) {		requrl = noUrl;	    } else {		requrl = u.toExternalForm();	    }	} else {	    requrl = urlst.toExternalForm();	}	StringBuffer sb = new StringBuffer(512);	String logs;	int status = reply.getStatus();	if ((status > 999) || (status < 0)) {	    status = 999; // means unknown	}	synchronized(sb) {	    byte ib[] = client.getInetAddress().getAddress();	    if (ib.length == 4) {		boolean doit;		for (int i=0; i< 4; i++) {		    doit = false;		    int b = ib[i];		    if (b < 0) {			b += 256;		    }		    if (b > 99) {			sb.append((char)('0' + (b / 100)));			b = b % 100;			doit = true;		    }		    if (doit || (b > 9)) {			sb.append((char)('0' + (b / 10)));			b = b % 10;		    }		    sb.append((char)('0'+b));		    if (i < 3) {			sb.append('.');		    }		}	    } else { // ipv6, let's be safe :)		sb.append(client.getInetAddress().getHostAddress());	    }	    sb.append(" - ");	    if (user == null) {		sb.append("- [");	    } else {		sb.append(user);		sb.append(" [");	    }	    dateCache(date, sb);	    sb.append("] \"");	    sb.append(request.getMethod());	    sb.append(' ');	    sb.append(requrl);	    sb.append(' ');	    sb.append(request.getVersion());	    sb.append("\" ");	    sb.append((char)('0'+ status / 100));	    status = status % 100;	    sb.append((char)('0'+ status / 10));	    status = status % 10;	    sb.append((char)('0'+ status));	    sb.append(' ');	    if (nbytes < 0) {		sb.append('-');	    } else {		sb.append(nbytes);	    }	    sb.append('\n');	    logs = sb.toString();	}	logmsg(logs);    }    public void log(String msg) {	logmsg(msg);    }    public void errlog (Client client, String msg) {	errlogmsg (client + ": " + msg + "\n") ;    }    public void errlog (String msg) {	errlogmsg (msg + "\n") ;    }    public void trace (Client client, String msg) {	tracemsg (client + ": " + msg + "\n") ;    }    public void trace (String msg) {	tracemsg (msg + "\n") ;    }    /**     * Get the name for the file indicated by the provided property.     * This method first looks for a property value. If none is found, it     * than constructs a default filename from the server root, by      * using the provided default name.     * <p>This method shall either succeed in getting a filename, or throw     * a runtime exception.     * @param propname The name of the property.     * @param def The default file name to use.     * @exception HTTPRuntimeException If no file name could be deduced from     *     the provided set of properties.     */    protected String getFilename (String propname, String def) {	String filename = props.getString (propname, null) ;	File flogdir = null;	if ( filename == null ) {	    String logdirname = props.getString(LOGDIRNAME_P, null);	    if ( logdirname == null) {		File root_dir = server.getRootDirectory();		if ( root_dir == null ) {		    String msg = "unable to build a default value for the \""			+ propname + "\" value." ;		    throw new HTTPRuntimeException (this.getClass().getName()						    , "getFilename"						    , msg) ;		}		flogdir = new File(root_dir, "logs") ;	    } else {		try {		    flogdir = new File(logdirname);		} catch (RuntimeException ex) {		    String msg = "unable to access log directory "+logdirname;		    throw new HTTPRuntimeException (this.getClass().getName()						    , "getFilename"						    , msg) ;		}	    }	    return (new File(flogdir, def)).getAbsolutePath() ;	} else {	    String logdirname = props.getString(LOGDIRNAME_P, null);	    if ( logdirname == null)		return filename ;	    try {		flogdir = new File(logdirname);	    } catch (RuntimeException ex) {		String msg = "unable to access log directory "+logdirname;		throw new HTTPRuntimeException (this.getClass().getName()						, "getFilename"						, msg) ;	    }	    return (new File(flogdir, filename)).getAbsolutePath() ;	}    }    /**     * Open this logger log file.     */    protected void openLogFile () {	if (rotateLevel > 0) {	    Date now = new Date();	    this.year = -1;	    checkLogFile(now);	} else {	    String logname = getFilename(LOGNAME_P, "log") ;	    try {		RandomAccessFile old = log ;		log = new RandomAccessFile (logname, "rw") ;		log.seek (log.length()) ;		if ( old != null )		    old.close () ;	    } catch (IOException e) {		throw new HTTPRuntimeException (this.getClass().getName()						, "openLogFile"						, "unable to open "+logname);	    }	}    }    /**     * Open this logger error log file.     */    protected void openErrorLogFile () {	String errlogname = getFilename (ERRLOGNAME_P, "errlog") ;	try {	    RandomAccessFile old = errlog ;	    errlog = new RandomAccessFile (errlogname, "rw") ;	    errlog.seek (errlog.length()) ;	    if ( old != null )		old.close() ;	} catch (IOException e) {	    throw new HTTPRuntimeException (this.getClass().getName()					    , "openErrorLogFile"					    , "unable to open "+errlogname);	}    }    /**     * Open this logger trace file.     */    protected void openTraceFile () {	String tracename = getFilename (TRACELOGNAME_P, "traces");	try {	    RandomAccessFile old = trace ;	    trace = new RandomAccessFile (tracename, "rw") ;	    trace.seek (trace.length()) ;	    if ( old != null )		old.close() ;	} catch (IOException e) {	    throw new HTTPRuntimeException (this.getClass().getName()					    , "openTraceFile"					    , "unable to open "+tracename);	}    }    /**     * Save all pending data to stable storage.     */    public synchronized void sync() {	try {	    if ((buffer != null) && (bufptr > 0)) {		log.write(buffer, 0, bufptr);		bufptr = 0;	    }	} catch (IOException ex) {	    server.errlog(getClass().getName()			  + ": IO exception in method sync \""                          + ex.getMessage() + "\".");	}    }    /**     * Shutdown this logger.     */    public synchronized void shutdown () {	server.getProperties().unregisterObserver (this) ;	try {	    // Flush any pending output:	    if ((buffer != null) && (bufptr > 0)) {		log.write(buffer, 0, bufptr);		bufptr = 0;	    }	    log.close() ; 	    log = null ;	    errlog.close() ;	    errlog = null ;	    trace.close() ;	    trace = null ;	} catch (IOException ex) {	    server.errlog(getClass().getName()			  + ": IO exception in method shutdown \""                          + ex.getMessage() + "\".");	}    }		    /**     * Initialize this logger for the given server.     * This method gets the server properties describe above to     * initialize its various log files.     * @param server The server to which thiss logger should initialize.     */    public void initialize (httpd server) {	this.server = server ;	this.props  = server.getProperties() ;	// Register for property changes:	props.registerObserver (this) ;        // init the rotation level        rotateLevel = props.getInteger(ROTATE_LEVEL_P, 0);	// Open the various logs:	openLogFile () ;	openErrorLogFile() ;	openTraceFile() ;	// Setup the log buffer is possible:	if ((bufsize = props.getInteger(BUFSIZE_P, bufsize)) > 0 ) 	    buffer = new byte[bufsize];	return ;    }	    /**     * Construct a new Logger instance.     */    CommonLogger () {	this.msgbuf = new byte[128] ;    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -