|
1 | 1 | package com.sap.hcp.cf.log4j2.converter; |
2 | 2 |
|
3 | 3 | import java.util.Arrays; |
| 4 | +import java.util.HashMap; |
4 | 5 | import java.util.Map; |
5 | 6 |
|
6 | 7 | import org.apache.logging.log4j.core.LogEvent; |
@@ -47,30 +48,38 @@ public static ContextPropsConverter newInstance(final String[] options) { |
47 | 48 |
|
48 | 49 | @Override |
49 | 50 | public void format(LogEvent event, StringBuilder toAppendTo) { |
50 | | - Map<String, String> contextData = event.getContextData().toMap(); |
51 | | - addCustomFieldsFromArguments(contextData, event); |
| 51 | + Map<String, String> contextData = event.getContextData().toMap(); |
| 52 | + contextData = addCustomFieldsFromArguments(contextData, event); |
52 | 53 | int lengthBefore = toAppendTo.length(); |
53 | | - converter.convert(toAppendTo, contextData); |
| 54 | + converter.convert(toAppendTo, contextData); |
54 | 55 | // remove comma from pattern, when no properties are added |
55 | 56 | // this is to avoid a double comma in the JSON |
56 | 57 | // Do not do this on empty messages |
57 | 58 | if (toAppendTo.length() == lengthBefore && lengthBefore > 0 && toAppendTo.charAt(lengthBefore - 1) == ',') { |
58 | 59 | toAppendTo.setLength(lengthBefore - 1); |
59 | 60 | } |
60 | | - } |
| 61 | + } |
61 | 62 |
|
62 | | - private void addCustomFieldsFromArguments(Map<String, String> contextData, LogEvent event) { |
63 | | - Message message = event.getMessage(); |
64 | | - Object[] parameters = message.getParameters(); |
65 | | - if (parameters == null) { |
66 | | - return; |
67 | | - } |
68 | | - for (Object current : parameters) { |
69 | | - if (current instanceof CustomField) { |
70 | | - CustomField field = (CustomField) current; |
71 | | - contextData.put(field.getKey(), field.getValue()); |
72 | | - } |
73 | | - } |
74 | | - } |
| 63 | + private Map<String, String> addCustomFieldsFromArguments(Map<String, String> contextData, LogEvent event) { |
| 64 | + Message message = event.getMessage(); |
| 65 | + Object[] parameters = message.getParameters(); |
| 66 | + if (parameters == null) { |
| 67 | + return contextData; |
| 68 | + } |
| 69 | + boolean unchangedContextData = true; |
| 70 | + Map<String, String> result = contextData; |
| 71 | + for (Object current: parameters) { |
| 72 | + if (current instanceof CustomField) { |
| 73 | + CustomField field = (CustomField) current; |
| 74 | + if (unchangedContextData) { |
| 75 | + // contextData might be an unmodifiable map |
| 76 | + result = new HashMap<>(contextData); |
| 77 | + unchangedContextData = false; |
| 78 | + } |
| 79 | + result.put(field.getKey(), field.getValue()); |
| 80 | + } |
| 81 | + } |
| 82 | + return result; |
| 83 | + } |
75 | 84 |
|
76 | 85 | } |
0 commit comments