AbstractLog4JLogger.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */
  20. package org.openspcoop2.utils.logger.log4j;

  21. import java.text.SimpleDateFormat;
  22. import java.util.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.Iterator;
  25. import java.util.List;
  26. import java.util.Map;

  27. import org.apache.logging.log4j.Level;
  28. import org.openspcoop2.utils.LoggerWrapperFactory;
  29. import org.openspcoop2.utils.UtilsException;
  30. import org.openspcoop2.utils.date.DateUtils;
  31. import org.openspcoop2.utils.logger.AbstractBasicLogger;
  32. import org.openspcoop2.utils.logger.IContext;
  33. import org.openspcoop2.utils.logger.beans.Attachment;
  34. import org.openspcoop2.utils.logger.beans.Diagnostic;
  35. import org.openspcoop2.utils.logger.beans.Event;
  36. import org.openspcoop2.utils.logger.beans.Message;
  37. import org.openspcoop2.utils.logger.beans.Property;
  38. import org.openspcoop2.utils.logger.config.DiagnosticConfig;
  39. import org.openspcoop2.utils.logger.config.Log4jConfig;
  40. import org.openspcoop2.utils.logger.constants.Severity;
  41. import org.slf4j.Logger;

  42. /**
  43.  * Log4JLogger
  44.  *
  45.  * @author Poli Andrea (apoli@link.it)
  46.  * @author $Author$
  47.  * @version $Rev$, $Date$
  48.  */
  49. public abstract class AbstractLog4JLogger extends AbstractBasicLogger  {


  50.     public AbstractLog4JLogger(DiagnosticConfig diagnosticConfig, Log4jConfig logConfig) throws UtilsException {
  51.         super(diagnosticConfig);
  52.        
  53.         Log4jConfig.validate(logConfig);
  54.         Log4jConfig.setConfigurationLogger(logConfig);
  55.        
  56.         this.logTransaction = LoggerWrapperFactory.getLogger("transaction");
  57.         if(this.logTransaction==null){
  58.             throw new UtilsException("Category [transaction] not found; expected in log4j configuration");
  59.         }
  60.        
  61.         this.logDiagnostic = LoggerWrapperFactory.getLoggerImpl("diagnostic");
  62.         if(this.logDiagnostic==null){
  63.             throw new UtilsException("Category [diagnostic] not found; expected in log4j configuration");
  64.         }
  65.        
  66.         this.logDump = LoggerWrapperFactory.getLogger("dump");
  67.         if(this.logDump==null){
  68.             throw new UtilsException("Category [dump] not found; expected in log4j configuration");
  69.         }
  70.        
  71.         this.logEvent = LoggerWrapperFactory.getLogger("event");
  72.         if(this.logEvent==null){
  73.             throw new UtilsException("Category [event] not found; expected in log4j configuration");
  74.         }
  75.        
  76.     }

  77.     protected Logger logTransaction;
  78.     protected org.apache.logging.log4j.Logger logDiagnostic;
  79.     protected Map<String, org.apache.logging.log4j.Logger> mapFunctionToLogDiagnostic = null;
  80.     protected Logger logDump;
  81.     protected Logger logEvent;
  82.    
  83.     private synchronized void initLogFunctionToDiagnostic(){
  84.         if(this.mapFunctionToLogDiagnostic==null){
  85.                
  86.             List<String> loggers = new ArrayList<>();
  87.             org.apache.logging.log4j.core.LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
  88.             Iterator<String> it = context.getConfiguration().getLoggers().keySet().iterator();
  89.             while (it.hasNext()) {
  90.                 String logger = (String) it.next();
  91.                 loggers.add(logger);
  92.             }

  93.             this.mapFunctionToLogDiagnostic = new HashMap<String, org.apache.logging.log4j.Logger>();
  94.             List<String> functions = this.diagnosticManager.getFunctions();
  95.             if(functions!=null && !functions.isEmpty()) {
  96.                 for (String function : functions) {
  97.                     //System.out.println("FUNCTION ["+function+"] ");
  98.                     if(loggers.contains("diagnostic."+function)){
  99.                         //System.out.println("REGISTRO");
  100.                         this.mapFunctionToLogDiagnostic.put(function, LoggerWrapperFactory.getLoggerImpl("diagnostic."+function));
  101.                     }
  102.                 }
  103.             }
  104.         }
  105.     }
  106.    
  107.     private static Severity diagnosticSeverity = Severity.DEBUG_HIGH;
  108.     public static void setDiagnosticSeverity(Severity logSeverity) {
  109.         if(logSeverity!=null){
  110.             diagnosticSeverity = logSeverity;
  111.         }
  112.     }
  113.     private static boolean emitDiagnostic(Severity severity){
  114.         return severity.intValue() <= diagnosticSeverity.intValue();
  115.     }
  116.    
  117.     private static Severity eventSeverity = Severity.DEBUG_HIGH;
  118.     public static void setEventSeverity(Severity logSeverity) {
  119.         if(logSeverity!=null){
  120.             eventSeverity = logSeverity;
  121.         }
  122.     }
  123.     private static boolean emitEvent(Severity severity){
  124.         return severity.intValue() <= eventSeverity.intValue();
  125.     }

  126.    
  127.     @Override
  128.     public void log() throws UtilsException {
  129.         this.log(this.getContext());
  130.     }
  131.    
  132.     @Override
  133.     public void log(IContext contextParam) throws UtilsException {
  134.                
  135.         StringBuilder showContext = new StringBuilder();
  136.         showContext.append("<").append(this.getContext().getIdTransaction()).append(">\n");
  137.        
  138.         this.logContext(contextParam, showContext);
  139.        
  140.         this.logTransaction.info(showContext.toString());
  141.        
  142.        
  143.     }
  144.     protected abstract void logContext(IContext contextParam, StringBuilder showContext);
  145.        

  146.     @Override
  147.     public void log(Event event) throws UtilsException {

  148.         StringBuilder out = new StringBuilder();

  149.         if(event.getSeverity()==null){
  150.             throw new UtilsException("Severity undefined");
  151.         }
  152.         if(emitEvent(event.getSeverity())==false){
  153.             return;
  154.         }
  155.        
  156.         if(this.getContext().getIdTransaction()!=null){
  157.             out.append("<").append(this.getContext().getIdTransaction()).append(">");
  158.             out.append(" \n");
  159.         }
  160.        
  161.         if(event.getDate()!=null){
  162.             SimpleDateFormat dateformat = DateUtils.getSimpleDateFormatMs();
  163.             out.append("Date:"+dateformat.format(event.getDate()));
  164.             out.append(" \n");
  165.         }
  166.        
  167.         if(event.getSeverity()!=null){
  168.             out.append("Severity:"+event.getSeverity().name());
  169.             out.append(" \n");
  170.         }
  171.                
  172.         if(event.getSource()!=null){
  173.             out.append("Source:"+event.getSource());
  174.             out.append(" \n");
  175.         }
  176.        
  177.         if(event.getCode()!=null){
  178.             out.append("Code:"+event.getCode());
  179.             out.append(" \n");
  180.         }
  181.        
  182.         if(event.getClusterId()!=null){
  183.             out.append("ClusterId:"+event.getClusterId());
  184.             out.append(" \n");
  185.         }
  186.        
  187.         if(event.getDescription()!=null){
  188.             out.append("Description:"+event.getDescription());
  189.             out.append(" \n");
  190.         }  
  191.        
  192.         if(event.getCorrelationIdentifier()!=null){
  193.             out.append("CorrelationIdentifier:"+event.getCorrelationIdentifier());
  194.             out.append(" \n");
  195.         }
  196.        
  197.         out.append("\n");
  198.        
  199.         this.logEvent.info(out.toString());
  200.     }

  201.     @Override
  202.     public String getLogParam(String logParam) throws UtilsException {
  203.         //throw new UtilsException("Not Implemented");
  204.         return "DEMOValoreCallback";
  205.     }
  206.    
  207.     protected abstract String getDomain(IContext contextParam);
  208.     protected abstract String getRequestIdentifier(IContext contextParam);
  209.     protected abstract String getResponseIdentifier(IContext contextParam);
  210.     protected abstract String getRequestCorrelationIdentifier(IContext contextParam);
  211.     protected abstract String getResponseCorrelationIdentifier(IContext contextParam);
  212.     protected abstract String getClient(IContext contextParam);
  213.     protected abstract String getClientPrincipal(IContext contextParam);
  214.     protected abstract String getFrom(IContext contextParam);
  215.     protected abstract String getTo(IContext contextParam);
  216.     protected abstract String getService(IContext contextParam);
  217.     protected abstract String getOperation(IContext contextParam);
  218.    
  219.     @Override
  220.     protected void log(Diagnostic diagnostic, IContext context) throws UtilsException {
  221.        
  222.         if(diagnostic.getSeverity()==null){
  223.             throw new UtilsException("Severity undefined");
  224.         }
  225.         if(emitDiagnostic(diagnostic.getSeverity())==false){
  226.             return;
  227.         }
  228.        
  229.         StringBuilder showMsg = new StringBuilder();
  230.        
  231.         if(diagnostic.getIdTransaction()!=null)
  232.             showMsg.append("<").append(diagnostic.getIdTransaction()).append(">");
  233.                
  234.         if(diagnostic.getCode()!=null){
  235.             if(showMsg.length()>0){
  236.                 showMsg.append(" ");
  237.             }
  238.             showMsg.append(diagnostic.getCode());
  239.             showMsg.append(" ");
  240.         }
  241.         if(this.getDomain(context)!=null){
  242.             showMsg.append(this.getDomain(context));
  243.             showMsg.append(".");
  244.         }
  245.         showMsg.append(diagnostic.getFunction());
  246.         showMsg.append(" <");
  247.         SimpleDateFormat dateformat = DateUtils.getSimpleDateFormatMs();
  248.         showMsg.append(dateformat.format(diagnostic.getDate()));
  249.         showMsg.append("> ");
  250.         showMsg.append("(");
  251.         showMsg.append(diagnostic.getSeverity().name());
  252.         showMsg.append(")");
  253.                
  254.         String idRichiesta = this.getRequestIdentifier(context);
  255.         String idRisposta = this.getResponseIdentifier(context);
  256.         if(idRichiesta!=null){
  257.             showMsg.append(" [id-req:").append(idRichiesta).append("]");
  258.         }
  259.         if(idRisposta!=null){
  260.             showMsg.append(" [id-resp:").append(idRisposta).append("]");
  261.         }
  262.        
  263.         String idCorrelazioneRichiesta = this.getRequestCorrelationIdentifier(context);
  264.         String idCorrelazioneRisposta = this.getResponseCorrelationIdentifier(context);
  265.         if(idCorrelazioneRichiesta!=null){
  266.             showMsg.append(" {correlation-req:").append(idCorrelazioneRichiesta).append("}");
  267.         }
  268.         if(idCorrelazioneRisposta!=null){
  269.             showMsg.append(" {correlation-resp:").append(idCorrelazioneRisposta).append("}");
  270.         }
  271.        
  272.         String client = this.getClient(context);
  273.         String clientPrincipal = this.getClientPrincipal(context);
  274.         if(client!=null){
  275.             showMsg.append(" Client:"+client);
  276.         }
  277.         else if(clientPrincipal!=null){
  278.             showMsg.append(" Client-Principal:"+clientPrincipal);
  279.         }
  280.        
  281.         String from = this.getFrom(context);
  282.         String to = this.getTo(context);
  283.         String service = this.getService(context);
  284.         String operation = this.getOperation(context);
  285.        
  286.         if(from!=null){
  287.             showMsg.append(" From:");
  288.             showMsg.append(from);
  289.         }
  290.         if( from!=null && (service!=null || to!=null))
  291.             showMsg.append(" -> ");
  292.        
  293.         if(to!=null){
  294.             showMsg.append(" To:");
  295.             showMsg.append(to);
  296.         }
  297.        
  298.         if(service!=null){
  299.             showMsg.append(" S:");
  300.             showMsg.append(service);
  301.         }
  302.        
  303.         if(operation!=null){
  304.             showMsg.append(" O:");
  305.             showMsg.append(operation);
  306.         }
  307.                
  308.         showMsg.append("\n");
  309.         showMsg.append(diagnostic.getMessage());
  310.         showMsg.append("\n");

  311.         org.apache.logging.log4j.Logger log = this.logDiagnostic;
  312.        
  313.         if(this.mapFunctionToLogDiagnostic==null){
  314.             this.initLogFunctionToDiagnostic();
  315.         }
  316.         if(this.mapFunctionToLogDiagnostic.containsKey(diagnostic.getFunction())){
  317.             log = this.mapFunctionToLogDiagnostic.get(diagnostic.getFunction());
  318.         }
  319.        
  320.         log.log(this.convertToPriority(diagnostic.getSeverity()), showMsg.toString());

  321.     }
  322.    
  323.     protected Level convertToPriority(Severity severity){
  324.         return SeverityLog4J.getSeverityLog4J(severity);
  325.     }

  326.     @Override
  327.     public void log(Message message) throws UtilsException {
  328.        
  329.         StringBuilder out = new StringBuilder();
  330.        
  331.         if(message.getIdTransaction()!=null){
  332.             out.append("<").append(message.getIdTransaction()).append(">");
  333.             out.append(" \n");
  334.         }
  335.         else if(this.getContext().getIdTransaction()!=null){
  336.             out.append("<").append(this.getContext().getIdTransaction()).append(">");
  337.             out.append(" \n");
  338.         }
  339.        
  340.         if(message.getIdMessage()!=null){
  341.             out.append("IdMessage:"+message.getIdMessage());
  342.             out.append(" \n");
  343.         }
  344.        
  345.         if(message.getIdServer()!=null){
  346.             out.append("IdServer:"+message.getIdServer());
  347.             out.append(" \n");
  348.         }
  349.        
  350.         if(message.getIdOperation()!=null){
  351.             out.append("IdOperation:"+message.getIdOperation());
  352.             out.append(" \n");
  353.         }
  354.        
  355.         if(message.getType()!=null){
  356.             out.append("Type:"+message.getType().name());
  357.             out.append(" \n");
  358.         }
  359.        
  360.         if(message.getContentType()!=null){
  361.             out.append("Content-Type:"+message.getContentType());
  362.             out.append(" \n");
  363.         }
  364.        
  365.         // HEADER
  366.         if(message.getHeaders()!=null && message.getHeaders().size()>0){
  367.             out.append("------ Header ------\n");
  368.             for (Property header : message.getHeadersAsList()) {
  369.                 out.append(header.getName()+"="+header.getValue()+"\n");
  370.             }
  371.         }
  372.        
  373.         // RESOURCES
  374.         if(message.getResources()!=null && message.getResources().size()>0){
  375.             out.append("------ Resource ------\n");
  376.             for (Property header : message.getResourcesAsList()) {
  377.                 out.append(header.getName()+"="+header.getValue()+"\n");
  378.             }
  379.         }
  380.        
  381.         // CONTENT
  382.         if(message.getContent()!=null){
  383.             out.append("------ Content ------\n");
  384.             out.append("Size:"+message.getContent().length+"\n");
  385.             // 1024 = 1K
  386.             // Visualizzo al massimo 250K
  387.             int max = 250 * 1024;
  388.             String text = null;
  389.             try{
  390.                 text = org.openspcoop2.utils.Utilities.convertToPrintableText(message.getContent(),max);
  391.             }catch(Exception e){
  392.                 text = e.getMessage();
  393.             }
  394.             out.append(text);
  395.             out.append("\n");
  396.         }
  397.        
  398.         // ATTACH
  399.         if(message.getAttachments()!=null && message.getAttachments().size()>0){
  400.             for (Attachment attachment : message.getAttachments()) {
  401.                 out.append("------ Attachment id["+attachment.getContentId()+"] ------\n");
  402.                 if(attachment.getContentType()!=null){
  403.                     out.append("Content-Type:"+attachment.getContentType());
  404.                     out.append(" \n");
  405.                 }
  406.                 if(attachment.getContent()!=null){
  407.                     out.append("Size:"+attachment.getContent().length+"\n");
  408.                     // 1024 = 1K
  409.                      // Visualizzo al massimo 250K
  410.                      int max = 250 * 1024;
  411.                      String text = null;
  412.                      try{
  413.                          text = org.openspcoop2.utils.Utilities.convertToPrintableText(attachment.getContent(),max);
  414.                      }catch(Exception e){
  415.                          text = e.getMessage();
  416.                      }
  417.                      out.append(text);
  418.                      out.append("\n");
  419.                 }
  420.             }
  421.         }
  422.        
  423.         out.append("\n");
  424.        
  425.         this.logDump.info(out.toString());
  426.     }
  427.    


  428.    

  429.    
  430. }