aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/ant/apache-ant-1.9.6/src/main/org/apache/tools/ant/listener/CommonsLoggingListener.java
blob: 32474eea30e0f02cc47378241a51dd844931c72c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package org.apache.tools.ant.listener;

import java.io.PrintStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogConfigurationException;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildListener;
import org.apache.tools.ant.BuildLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.UnknownElement;


/**
 * Jakarta Commons Logging listener.
 * Note: do not use the SimpleLog as your logger implementation as it
 * causes an infinite loop since it writes to System.err, which Ant traps
 * and reroutes to the logger/listener layer.
 *
 * The following names are used for the log:
 *  org.apache.tools.ant.Project.PROJECT_NAME  - for project events
 *  org.apache.tools.ant.Target.TARGET_NAME - for target events
 *  TASK_CLASS_NAME.TARGET_NAME - for events in individual targets.
 *
 * In all target and project names we replace "." and " " with "-".
 *
 * TODO: we should use the advanced context logging features (and expose them
 * in c-l first :-)
 * TODO: this is _very_ inefficient. Switching the out and tracking the logs
 * can be optimized a lot - but may require few more changes to the core.
 *
 * @since Ant 1.5
 */
public class CommonsLoggingListener implements BuildListener, BuildLogger {

    /** Indicates if the listener was initialized. */
    private boolean initialized = false;

    private LogFactory logFactory;

    /**
     * name of the category under which target events are logged
     */
    public static final String TARGET_LOG = "org.apache.tools.ant.Target";
    /**
     * name of the category under which project events are logged
     */
    public static final String PROJECT_LOG = "org.apache.tools.ant.Project";

    /**
     * Construct the listener and make sure that a LogFactory
     * can be obtained.
     */
    public CommonsLoggingListener() {
    }

    private Log getLog(String cat, String suffix) {
        if (suffix != null) {
            suffix = suffix.replace('.', '-');
            suffix = suffix.replace(' ', '-');
            cat = cat + "." + suffix;
        }
        final PrintStream tmpOut = System.out;
        final PrintStream tmpErr = System.err;
        System.setOut(out);
        System.setErr(err);

        if (!initialized) {
            try {
                logFactory = LogFactory.getFactory();
            } catch (final LogConfigurationException e) {
                e.printStackTrace(System.err);
                return null;
            }
        }

        initialized = true;
        final Log log = logFactory.getInstance(cat);
        System.setOut(tmpOut);
        System.setErr(tmpErr);
        return log;
    }

    /** {@inheritDoc}. */
    public void buildStarted(final BuildEvent event) {
        final String categoryString = PROJECT_LOG;
        final Log log = getLog(categoryString, null);

        if (initialized) {
            realLog(log, "Build started.", Project.MSG_INFO, null);
        }
    }

    /** {@inheritDoc}. */
    public void buildFinished(final BuildEvent event) {
        if (initialized) {
            final String categoryString = PROJECT_LOG;
            final Log log = getLog(categoryString, event.getProject().getName());

            if (event.getException() == null) {
                realLog(log, "Build finished.", Project.MSG_INFO, null);
            } else {
                realLog(log, "Build finished with error.", Project.MSG_ERR,
                        event.getException());
            }
        }
    }

    /**
     * @see BuildListener#targetStarted
     */
    /** {@inheritDoc}. */
    public void targetStarted(final BuildEvent event) {
        if (initialized) {
            final Log log = getLog(TARGET_LOG,
                    event.getTarget().getName());
            // Since task log category includes target, we don't really
            // need this message
            realLog(log, "Start: " + event.getTarget().getName(),
                    Project.MSG_VERBOSE, null);
        }
    }

    /**
     * @see BuildListener#targetFinished
     */
    /** {@inheritDoc}. */
    public void targetFinished(final BuildEvent event) {
        if (initialized) {
            final String targetName = event.getTarget().getName();
            final Log log = getLog(TARGET_LOG,
                    event.getTarget().getName());
            if (event.getException() == null) {
                realLog(log, "Target end: " + targetName, Project.MSG_DEBUG, null);
            } else {
                realLog(log, "Target \"" + targetName
                        + "\" finished with error.", Project.MSG_ERR,
                        event.getException());
            }
        }
    }

    /**
     * @see BuildListener#taskStarted
     */
    /** {@inheritDoc}. */
    public void taskStarted(final BuildEvent event) {
        if (initialized) {
            final Task task = event.getTask();
            Object real = task;
            if (task instanceof UnknownElement) {
                final Object realObj = ((UnknownElement) task).getTask();
                if (realObj != null) {
                    real = realObj;
                }
            }
            final Log log = getLog(real.getClass().getName(), null);
            if (log.isTraceEnabled()) {
                realLog(log, "Task \"" + task.getTaskName() + "\" started ",
                        Project.MSG_VERBOSE, null);
            }
        }
    }

    /**
     * @see BuildListener#taskFinished
     */
    /** {@inheritDoc}. */
    public void taskFinished(final BuildEvent event) {
        if (initialized) {
            final Task task = event.getTask();
            Object real = task;
            if (task instanceof UnknownElement) {
                final Object realObj = ((UnknownElement) task).getTask();
                if (realObj != null) {
                    real = realObj;
                }
            }
            final Log log = getLog(real.getClass().getName(), null);
            if (event.getException() == null) {
                if (log.isTraceEnabled()) {
                    realLog(log, "Task \"" + task.getTaskName() + "\" finished.",
                            Project.MSG_VERBOSE, null);
                }
            } else {
                realLog(log, "Task \"" + task.getTaskName()
                        + "\" finished with error.", Project.MSG_ERR,
                        event.getException());
            }
        }
    }


    /**
     * @see BuildListener#messageLogged
     */
    /** {@inheritDoc}. */
    public void messageLogged(final BuildEvent event) {
        if (initialized) {
            Object categoryObject = event.getTask();
            String categoryString = null;
            String categoryDetail = null;

            if (categoryObject == null) {
                categoryObject = event.getTarget();
                if (categoryObject == null) {
                    categoryObject = event.getProject();
                    categoryString = PROJECT_LOG;
                    categoryDetail = event.getProject().getName();
                } else {
                    categoryString = TARGET_LOG;
                    categoryDetail = event.getTarget().getName();
                }
            } else {
                // It's a task - append the target
                if (event.getTarget() != null) {
                    categoryString = categoryObject.getClass().getName();
                    categoryDetail = event.getTarget().getName();
                } else {
                    categoryString = categoryObject.getClass().getName();
                }

            }

            final Log log = getLog(categoryString, categoryDetail);
            final int priority = event.getPriority();
            final String message = event.getMessage();
            realLog(log, message, priority , null);
        }
    }

    private void realLog(final Log log, final String message, final int priority, final Throwable t) {
        final PrintStream tmpOut = System.out;
        final PrintStream tmpErr = System.err;
        System.setOut(out);
        System.setErr(err);
        switch (priority) {
            case Project.MSG_ERR:
                if (t == null) {
                    log.error(message);
                } else {
                    log.error(message, t);
                }
                break;
            case Project.MSG_WARN:
                if (t == null) {
                    log.warn(message);
                } else {
                    log.warn(message, t);
                }
                break;
            case Project.MSG_INFO:
                if (t == null) {
                    log.info(message);
                } else {
                    log.info(message, t);
                }
                break;
            case Project.MSG_VERBOSE:
                log.debug(message);
                break;
            case Project.MSG_DEBUG:
                log.debug(message);
                break;
            default:
                log.error(message);
                break;
        }
        System.setOut(tmpOut);
        System.setErr(tmpErr);
    }

    // CheckStyle:VisibilityModifier OFF - bc
    PrintStream out = System.out;
    PrintStream err = System.err;
    // CheckStyle:VisibilityModifier ON

    /**
     * Set the the output level.
     * This is not used, the logger config is used instead.
     * @param level ignored
     */
    public void setMessageOutputLevel(final int level) {
        // Use the logger config
    }

    /**
     * Set the output print stream.
     * @param output the output stream
     */
    public void setOutputPrintStream(final PrintStream output) {
        this.out = output;
    }

    /**
     * Set emacs mode.
     * This is ignored.
     * @param emacsMode ignored
     */
    public void setEmacsMode(final boolean emacsMode) {
        // Doesn't make sense for c-l. Use the logger config
    }

    /**
     * Set the error print stream.
     * @param err the error stream
     */
    public void setErrorPrintStream(final PrintStream err) {
        this.err = err;
    }

}