Skip to content

Instantly share code, notes, and snippets.

@brianmfear
Created April 5, 2022 10:30
Show Gist options
  • Save brianmfear/cc372aba7728415a61bb0703b98a58da to your computer and use it in GitHub Desktop.
Save brianmfear/cc372aba7728415a61bb0703b98a58da to your computer and use it in GitHub Desktop.
Sample Logger in Apex (does not store the logs; do whatever you want here)
public class Logger {
static Pattern thePattern = Pattern.compile(
'(?i)^(?:class\\.)?([^.]+)\\.?([^\\.\\:]+)?[\\.\\:]?([^\\.\\:]*): line (\\d+), column (\\d+)$'
);
static Log__c[] logs = new Log__c[0];
static LoggingLevel controlLevel = LoggingLevel.DEBUG;
public static void addLog(String message) {
addLog(new DmlException(), controlLevel, message, null);
}
public static void addLog(String message, Object value) {
addLog(new DmlException(), controlLevel, message, value);
}
public static void addLog(LoggingLevel level, String message) {
addLog(new DmlException(), level, message, null);
}
public static void addLog(LoggingLevel level, String message, Object value) {
addLog(new DmlException(), level, message, value);
}
static void addLog(Exception ex, LoggingLevel level, String message, Object value) {
if(level.ordinal() > controlLevel.ordinal()) {
return;
}
Matcher m = thePattern.matcher(ex.getStackTraceString().split('\n',3)[1]);
String className, methodName, line, column;
if(m.find()) {
String[] groups = new String[] { m.group(1), m.group(2), m.group(3), m.group(4), m.group(5)};
if(String.isBlank(groups[3])) {
className = groups[0];
methodName = groups[1];
} else {
className = groups[0] + '.' + groups[1];
methodName = groups[2];
}
line = groups[4];
column = groups[5];
// Write your output/log files here
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment