1 package org.slf4j.agent;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5 import java.lang.instrument.Instrumentation;
6 import java.util.Date;
7 import java.util.Properties;
8
9 import org.slf4j.instrumentation.LogTransformer;
10
11
12
13
14
15 public class AgentPremain {
16
17
18
19
20
21
22
23
24
25
26
27
28 public static void premain(String agentArgument,
29 Instrumentation instrumentation) {
30
31
32
33
34 LogTransformer.Builder builder = new LogTransformer.Builder();
35 builder = builder.addEntryExit(true);
36
37 if (agentArgument != null) {
38 Properties args = parseArguments(agentArgument, ",");
39
40 if (args.containsKey(AgentOptions.VERBOSE)) {
41 builder = builder.verbose(true);
42 }
43
44 if (args.containsKey(AgentOptions.TIME)) {
45 printStartStopTimes();
46 }
47
48 if (args.containsKey(AgentOptions.IGNORE)) {
49 String ignore = args.getProperty(AgentOptions.IGNORE);
50 builder = builder.ignore(ignore.split(":"));
51 }
52
53 if (args.containsKey(AgentOptions.LEVEL)) {
54 builder = builder.level(args.getProperty(AgentOptions.LEVEL));
55 }
56 }
57
58 instrumentation.addTransformer(builder.build());
59 }
60
61
62
63
64
65
66
67
68
69
70
71
72
73 private static Properties parseArguments(String agentArgument,
74 String separator) {
75 Properties p = new Properties();
76 try {
77 String argumentAsLines = agentArgument.replaceAll(separator, "\n");
78 p.load(new ByteArrayInputStream(argumentAsLines.getBytes()));
79 } catch (IOException e) {
80 String s = "Could not load arguments as properties";
81 throw new RuntimeException(s, e);
82 }
83 return p;
84 }
85
86
87
88
89
90
91
92 private static void printStartStopTimes() {
93 final long start = System.currentTimeMillis();
94
95 System.err.println("Start at " + new Date());
96
97 Thread hook = new Thread() {
98 @Override
99 public void run() {
100 long timePassed = System.currentTimeMillis() - start;
101 System.err.println("Stop at " + new Date()
102 + ", execution time = " + timePassed + " ms");
103 }
104 };
105 Runtime.getRuntime().addShutdownHook(hook);
106 }
107 }