View Javadoc

1   /*
2    * $Id: PrettyLoggingFeature.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.module.cxf.feature;
12  
13  import org.mule.api.MuleException;
14  import org.mule.module.xml.transformer.XmlPrettyPrinter;
15  import org.mule.util.StringUtils;
16  
17  import org.apache.cxf.Bus;
18  import org.apache.cxf.feature.LoggingFeature;
19  import org.apache.cxf.interceptor.InterceptorProvider;
20  
21  /**
22   * Same as the standard CXF LoggingFeature, but with pretty-printed XML 
23   * for the message payload.
24   */
25  public class PrettyLoggingFeature extends LoggingFeature
26  {
27      @Override
28      protected void initializeProvider(InterceptorProvider provider, Bus bus)
29      {
30          provider.getInInterceptors().add(new PrettyLoggingInInterceptor(getLimit()));
31          provider.getOutInterceptors().add(new PrettyLoggingOutInterceptor(getLimit()));
32      }
33      
34      /**
35       * Takes the log output from the standard CXF LoggingInterceptor, 
36       * disassembles it, pretty-prints the XML payload, then puts it all back 
37       * together again.
38       */
39      protected static String formatXmlPayload(String originalLogString)
40      {
41          String[] lines = originalLogString.split("\n");
42          
43          // Figure out which line has the payload on it
44          int payloadLine = -1;
45          for (int i=0; i<lines.length; ++i)
46          {
47              if (lines[i].startsWith("Payload: "))
48              {
49                  payloadLine = i;
50                  break;
51              }
52          }
53          if (payloadLine == -1)
54          {
55              System.err.println("Could not find a line which begins with 'Payload: '");
56              return originalLogString;
57          }
58          
59          // Extract the XML payload and format it
60          String payload = lines[payloadLine];
61          String xml = StringUtils.substringAfter(payload, "Payload: ");
62          XmlPrettyPrinter pp = new XmlPrettyPrinter();
63          try
64          {
65              xml = (String) pp.transform(xml);
66          }
67          catch (MuleException e)
68          {
69              System.err.println(e.getMessage());
70          }
71          
72          // Replace the payload line with the formatted XML and put it all back together again
73          lines[payloadLine] = "Payload: \n" + xml;
74          return StringUtils.join(lines, "\n");
75      }
76  }