2010-01-22 5 views
8

Comment rediriger javax.mail.Session setDebugOut vers log4j logger?Comment faire pour rediriger javax.mail.Session setDebugOut vers log4j logger?

Est-il possible de rediriger uniquement le débogage mailSession vers l'enregistreur?

Je veux dire, il existe des solutions comme

link text

qui réaffecte toutes les sorties standard pour aller à LOG4J

--System.setOut (nouveau Log4jStream())

Cordialement

+1

Je suis tombé sur ce vieux billet. Il est maintenant aussi possible d'utiliser un pont jul-> slf4j 'java.util.logging.Logger.getLogger (" javax.mail ")' sans utiliser l'option de débogage PrintStream. –

Répondre

2

Écrivez votre propre classe OutputStream

et

mailSession.setDebugOut (nouveau PrintStream (votre objet de flux aoutput personnalisé));

10

bibliothèque contient Apache Commons Exec classe utile LogOutputStream, que vous pouvez utiliser à cette fin précise:

LogOutputStream losStdOut = new LogOutputStream() {    
    @Override 
    protected void processLine(String line, int level) { 
     cat.debug(line); 
    } 
}; 

Session session = Session.getDefaultInstance(new Properties(), null); 
session.setDebugOut(new PrintStream(losStdOut)); 

chat est évidemment log4j Catégorie/Appender.

3

i créé un propre FilterOutputStream (vous pouvez aussi utiliser le org.apache.logging.Logger au lieu de la FSL)

public class LogStream extends FilterOutputStream 
    { 
     private static org.slf4j.Logger    LOG = org.slf4j.LoggerFactory.getLogger(LogStream.class); 
     private static final OutputStream bos = new ByteArrayOutputStream(); 

     public LogStream(OutputStream out) 
      { 
       // initialize parent with my bytearray (which was never used) 
       super(bos); 
      } 

     @Override 
     public void flush() throws IOException 
      { 
       // this was never called in my test 
       bos.flush(); 
       if (bos.size() > 0) LOG.info(bos.toString()); 
       bos.reset(); 
      } 

     @Override 
     public void write(byte[] b) throws IOException 
      { 
       LOG.info(new String(b)); 
      } 

     @Override 
     public void write(byte[] b, int off, int len) throws IOException 
      { 
       LOG.info(new String(b, off, len)); 
      } 

     @Override 
     public void write(int b) throws IOException 
      { 
       write(new byte[] { (byte) b }); 
      } 
    } 

alors je réexpédié la javamail à ma sortie

// redirect the output to our logstream 
javax.mail.Session def = javax.mail.Session.getDefaultInstance(new Properties()); 
def.setDebugOut(new PrintStream(new LogStream(null))); 
def.setDebug(true); 

que a fait l'affaire :)