View Javadoc

1   package org.apache.mina.util;
2   
3   import java.util.logging.Level;
4   import java.util.logging.Logger;
5   
6   import org.apache.mina.common.Session;
7   import org.apache.mina.io.IoSession;
8   import org.apache.mina.protocol.ProtocolSession;
9   
10  /***
11   * Call {@link #getLogger(Session)}, {@link #log(Level,Session, String)}, and
12   * {@link #log(Level,Session, String, Throwable)} to log protocol-specific messages.
13   * <p>
14   * Set {@link #PREFIX} and {@link #LOGGER} session attributes
15   * to override prefix string, logger, and log level.
16   *
17   * @author The Apache Directory Project (dev@directory.apache.org)
18   * @author Trustin Lee (trustin@apache.org)
19   * @version $Rev: 165596 $, $Date: 2005-05-02 16:22:02 +0900 (?, 02  5? 2005) $
20   *
21   */
22  public class SessionLog {
23      /***
24       * Session attribute key: prefix string
25       */
26      public static final String PREFIX = SessionLog.class.getName() + ".prefix";
27  
28      /***
29       * Session attribute key: {@link Logger}
30       */
31      public static final String LOGGER = SessionLog.class.getName() + ".logger";
32      
33      public static Logger getLogger( Session session )
34      {
35          
36          Logger log = (Logger) session.getAttribute( LOGGER );
37          if( log == null )
38          {
39              log = Logger.getLogger( getClassName( session ) );
40              String prefix = ( String ) session.getAttribute( PREFIX );
41              if( prefix == null )
42              {
43                  prefix = "[" + session.getRemoteAddress() + "] ";
44                  session.setAttribute( PREFIX, prefix );
45              }
46                  
47              session.setAttribute( LOGGER, log );
48          }
49          
50          return log;
51      }
52      
53      private static String getClassName( Session session )
54      {
55          if( session instanceof IoSession )
56              return ( ( IoSession ) session ).getHandler().getClass().getName();
57          else
58              return ( ( ProtocolSession ) session ).getHandler().getClass().getName();
59      }
60  
61      public static void log( Level level, Session session, String message )
62      {
63          Logger log = getLogger( session );
64          if( log.isLoggable( level ) )
65          {
66              log.log( level, message );
67          }
68      }
69  
70      public static void log( Level level, Session session, String message, Throwable cause )
71      {
72          Logger log = getLogger( session );
73          if( log.isLoggable( level ) )
74          {
75              log.log( level, message, cause );
76          }
77      }
78  }