Codebase list libslf4j-java / upstream/1.7.26
New upstream version 1.7.26 Emmanuel Bourg 3 years ago
337 changed file(s) with 31830 addition(s) and 31043 deletion(s). Raw diff Collapse all Expand all
0 # Auto detect text files and perform LF normalization
1 * text=auto
2
3 # Custom for Visual Studio
4 *.cs diff=csharp
5 *.sln merge=union
6 *.csproj merge=union
7 *.vbproj merge=union
8 *.fsproj merge=union
9 *.dbproj merge=union
10
11 # Standard to msysgit
12 *.doc diff=astextplain
13 *.DOC diff=astextplain
14 *.docx diff=astextplain
15 *.DOCX diff=astextplain
16 *.dot diff=astextplain
17 *.DOT diff=astextplain
18 *.pdf diff=astextplain
19 *.PDF diff=astextplain
20 *.rtf diff=astextplain
21 *.RTF diff=astextplain
0 .settings
1 target
2 .classpath
3 .project
4 *~
5 *.tmproj
6 *.iml
7 .idea
8 .scala_dependencies
9 integration/bundle/
10 integration/felix-cache/
11 runner
12 .DS_Store
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project version="4">
2 <component name="ProjectCodeStyleSettingsManager">
3 <option name="PER_PROJECT_SETTINGS">
4 <value>
5 <option name="OTHER_INDENT_OPTIONS">
6 <value>
7 <option name="INDENT_SIZE" value="2" />
8 <option name="CONTINUATION_INDENT_SIZE" value="8" />
9 <option name="TAB_SIZE" value="2" />
10 <option name="USE_TAB_CHARACTER" value="false" />
11 <option name="SMART_TABS" value="false" />
12 <option name="LABEL_INDENT_SIZE" value="0" />
13 <option name="LABEL_INDENT_ABSOLUTE" value="false" />
14 <option name="USE_RELATIVE_INDENTS" value="false" />
15 </value>
16 </option>
17 <XML>
18 <option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
19 </XML>
20 <codeStyleSettings language="JAVA">
21 <option name="RIGHT_MARGIN" value="120" />
22 <option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
23 <option name="SPACE_BEFORE_IF_PARENTHESES" value="false" />
24 <option name="SPACE_BEFORE_WHILE_PARENTHESES" value="false" />
25 <option name="SPACE_BEFORE_FOR_PARENTHESES" value="false" />
26 <option name="SPACE_BEFORE_TRY_PARENTHESES" value="false" />
27 <option name="SPACE_BEFORE_SWITCH_PARENTHESES" value="false" />
28 <option name="SPACE_BEFORE_SYNCHRONIZED_PARENTHESES" value="false" />
29 <option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
30 <option name="KEEP_SIMPLE_CLASSES_IN_ONE_LINE" value="true" />
31 <option name="KEEP_MULTIPLE_EXPRESSIONS_IN_ONE_LINE" value="true" />
32 <indentOptions>
33 <option name="INDENT_SIZE" value="2" />
34 <option name="TAB_SIZE" value="2" />
35 </indentOptions>
36 </codeStyleSettings>
37 <codeStyleSettings language="XML">
38 <indentOptions>
39 <option name="INDENT_SIZE" value="2" />
40 <option name="TAB_SIZE" value="2" />
41 </indentOptions>
42 </codeStyleSettings>
43 </value>
44 </option>
45 <option name="USE_PER_PROJECT_SETTINGS" value="true" />
46 </component>
47 </project>
0 language: java
1 notifications:
2 email:
3 - notification@qos.ch
0 Copyright (c) 2004-2017 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
0 Copyright (c) 2004-2017 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
0 # About SLF4J
1 The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.
2 More information can be found on the [SLF4J website](http://www.slf4j.org).
3 # Build Status
4 [![Build Status](https://travis-ci.org/qos-ch/slf4j.png)](https://travis-ci.org/qos-ch/slf4j)
5
6 # How to contribute pull requests
7 If you are interested in improving SLF4J, great! The SLF4J community looks forward to your contribution. Please follow this process:
8
9 1. Start a discussion on the [slf4j-dev mailing list](http://www.slf4j.org/mailing-lists.html) about your proposed change. Alternately file a [bug report](http://www.slf4j.org/bug-reporting.html).
10 2. Fork qos-ch/slf4j. Ideally, create a new branch from your fork for your contribution to make it easier to merge your changes back.
11 3. Make your changes on the branch you hopefuly created in Step 2. Be sure that your code passes existing unit tests. Please add unit tests for your work if appropriate. It usually is.
12 4. Push your changes to your fork/branch in github. Don't push it to your master! If you do it will make it harder to submit new changes later.
13 5. Submit a pull request to SLF4J from from your commit page on github.
0 # About SLF4J
1 The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.
2 More information can be found on the [SLF4J website](http://www.slf4j.org).
3 # Build Status
4 [![Build Status](https://travis-ci.org/qos-ch/slf4j.png)](https://travis-ci.org/qos-ch/slf4j)
5
6 # How to contribute pull requests
7 If you are interested in improving SLF4J, great! The SLF4J community looks forward to your contribution. Please follow this process:
8
9 1. Start a discussion on the [slf4j-dev mailing list](http://www.slf4j.org/mailing-lists.html) about your proposed change. Alternately file a [bug report](http://www.slf4j.org/bug-reporting.html).
10 2. Fork qos-ch/slf4j. Ideally, create a new branch from your fork for your contribution to make it easier to merge your changes back.
11 3. Make your changes on the branch you hopefuly created in Step 2. Be sure that your code passes existing unit tests. Please add unit tests for your work if appropriate. It usually is.
12 4. Push your changes to your fork/branch in github. Don't push it to your master! If you do it will make it harder to submit new changes later.
13 5. Submit a pull request to SLF4J from from your commit page on github.
0 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
1 <profiles version="12">
2 <profile kind="CodeFormatterProfile" name="slf4jCodeStyle" version="12">
3 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
4 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
5 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>
6 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
7 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
8 <setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>
9 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
10 <setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="insert"/>
11 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>
12 <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
13 <setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
14 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
15 <setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
16 <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
17 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
18 <setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="false"/>
19 <setting id="org.eclipse.jdt.core.formatter.indentation.size" value="8"/>
20 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
21 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
22 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
23 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
24 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="insert"/>
25 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
26 <setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
27 <setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="4"/>
28 <setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/>
29 <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="1"/>
30 <setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
31 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
32 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
33 <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
34 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
35 <setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>
36 <setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/>
37 <setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>
38 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
39 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
40 <setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
41 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
42 <setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
43 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>
44 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
45 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
46 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
47 <setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/>
48 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>
49 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
50 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
51 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
52 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>
53 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
54 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
55 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
56 <setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
57 <setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>
58 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
59 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
60 <setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
61 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>
62 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
63 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
64 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
65 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
66 <setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="120"/>
67 <setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="false"/>
68 <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
69 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
70 <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
71 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
72 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
73 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
74 <setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>
75 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>
76 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>
77 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
78 <setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/>
79 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
80 <setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
81 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="insert"/>
82 <setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
83 <setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>
84 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
85 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
86 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
87 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
88 <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
89 <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
90 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
91 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
92 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
93 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
94 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>
95 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_lambda_body" value="end_of_line"/>
96 <setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
97 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
98 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
99 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
100 <setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="true"/>
101 <setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
102 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
103 <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
104 <setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
105 <setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>
106 <setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>
107 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
108 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/>
109 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="do not insert"/>
110 <setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
111 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
112 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
113 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
114 <setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
115 <setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>
116 <setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>
117 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
118 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
119 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/>
120 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
121 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
122 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
123 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
124 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
125 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
126 <setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>
127 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
128 <setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
129 <setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="0"/>
130 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="insert"/>
131 <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
132 <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
133 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
134 <setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
135 <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
136 <setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
137 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>
138 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
139 <setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
140 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
141 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>
142 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
143 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>
144 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>
145 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
146 <setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/>
147 <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
148 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
149 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
150 <setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>
151 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
152 <setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/>
153 <setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>
154 <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
155 <setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
156 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
157 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
158 <setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>
159 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>
160 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
161 <setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>
162 <setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>
163 <setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
164 <setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
165 <setting id="org.eclipse.jdt.core.compiler.source" value="1.8"/>
166 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
167 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
168 <setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
169 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="insert"/>
170 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
171 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
172 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
173 <setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="false"/>
174 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
175 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>
176 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>
177 <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
178 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
179 <setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
180 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
181 <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
182 <setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
183 <setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
184 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>
185 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
186 <setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.8"/>
187 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>
188 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
189 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
190 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation" value="do not insert"/>
191 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>
192 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
193 <setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="false"/>
194 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
195 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
196 <setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
197 <setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
198 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
199 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
200 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
201 <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="0"/>
202 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
203 <setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
204 <setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="false"/>
205 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
206 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
207 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
208 <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
209 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>
210 <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
211 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
212 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
213 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
214 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
215 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
216 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
217 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
218 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
219 <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/>
220 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
221 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
222 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
223 <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
224 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
225 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
226 <setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
227 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
228 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
229 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
230 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
231 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/>
232 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
233 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
234 <setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/>
235 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow" value="insert"/>
236 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
237 <setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
238 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
239 <setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
240 <setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
241 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
242 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
243 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
244 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
245 <setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
246 <setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
247 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
248 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
249 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
250 <setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/>
251 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
252 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
253 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
254 <setting id="org.eclipse.jdt.core.compiler.compliance" value="1.8"/>
255 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
256 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
257 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
258 <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
259 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
260 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
261 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
262 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
263 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
264 <setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/>
265 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
266 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>
267 <setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>
268 <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
269 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
270 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
271 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
272 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
273 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
274 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
275 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
276 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
277 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
278 <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
279 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow" value="insert"/>
280 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
281 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
282 <setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>
283 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
284 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
285 <setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="true"/>
286 <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
287 <setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
288 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
289 <setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/>
290 <setting id="org.eclipse.jdt.core.formatter.lineSplit" value="160"/>
291 <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
292 <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
293 </profile>
294 </profiles>
0 <project name="integration" default="testAll" basedir=".">
1
2 <!--
3 This build file is usually run indirectly via Maven.
4
5 When running this build file through Ant directly, you must
6 define the currentVersion property on the command line, e.g.:
7
8 ant -DcurrentVersion=1.5.4-SNAPSHOT
9 -->
10
11 <echo message="compile classpath: ${compile_classpath}" />
12 <echo message="runtime classpath: ${runtime_classpath}" />
13 <echo message="test classpath: ${test_classpath}" />
14 <echo message="plugin classpath: ${plugin_classpath}" />
15 <echo message="basedir: ${basedir}" />
16
17
18 <!--<property name="path_to_policy" value="file:./integration/src/policy/java-under-ant.policy"/>-->
19
20
21 <path id="path142Binding">
22 <pathelement location="target/test-classes/" />
23 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
24 <pathelement location="./lib/slf4j-simple-1.4.2.jar" />
25 </path >
26
27 <path id="path150Binding">
28 <pathelement location="target/test-classes/" />
29 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
30 <pathelement location="./lib/slf4j-simple-1.5.0.jar" />
31 </path >
32
33 <path id="path1511API">
34 <pathelement location="target/test-classes/" />
35 <pathelement location="./lib/slf4j-api-1.5.11.jar" />
36 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
37 </path >
38
39 <path id="path1511Binding">
40 <pathelement location="target/test-classes/" />
41 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
42 <pathelement location="./lib/slf4j-simple-1.5.11.jar" />
43 </path >
44
45 <!--<path id="pathIncompatible">
46 <pathelement location="target/test-classes/" />
47 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
48 <pathelement location="./lib/slf4j-simple-INCOMPATIBLE.jar" />
49 </path >
50 -->
51
52 <path id="pathCurrent">
53 <pathelement location="target/test-classes/" />
54 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
55 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
56 </path >
57
58
59 <path id="incompatibleMultiBinding">
60 <pathelement location="target/test-classes/" />
61 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
62 <pathelement location="./lib/slf4j-simple-1.5.0.jar" />
63 <pathelement location="./lib/slf4j-nop-1.5.6.jar" />
64 </path >
65
66 <path id="multiBinding">
67 <pathelement location="target/test-classes/" />
68 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
69 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
70 <pathelement location="../slf4j-nop/target/slf4j-nop-${currentVersion}.jar" />
71 </path >
72
73 <path id="binding166">
74 <pathelement location="target/test-classes/" />
75 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
76 <pathelement location="./lib/slf4j-simple-1.6.6.jar" />
77 </path >
78
79 <path id="binding2099">
80 <pathelement location="target/test-classes/" />
81 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
82 <pathelement location="./lib/slf4j-simple-2.0.99.jar" />
83 </path >
84
85
86 <path id="api166">
87 <pathelement location="target/test-classes/" />
88 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
89 <pathelement location="./lib/slf4j-api-1.6.6.jar" />
90 </path >
91
92
93 <!-- this is really very ugly, but it's the only way to circumvent
94 http://jira.codehaus.org/browse/MANTRUN-95
95 -->
96 <taskdef name="junit" classpath="${plugin_classpath};${compile_classpath}"
97 classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTask" />
98
99 <target name="init">
100 <mkdir dir="target/unit-reports" />
101 </target>
102
103 <target name="testAll" depends="init,
104 testMissingSingletonMethod,
105 testMismatch,
106 testMatch,
107 testMultiBinding,
108 testIncompatibleMultiBinding,
109 testFuture_16Series,
110 testActiveSecurityManager">
111 </target>
112
113
114 <target name="testMissingSingletonMethod">
115
116 <junit printsummary="yes" fork="no" haltonfailure="yes">
117 <classpath refid="path142Binding" />
118 <formatter type="plain" />
119 <test fork="yes" todir="target/unit-reports"
120 outfile="TEST-142BININDING"
121 name="org.slf4j.MissingSingletonMethodAssertionTest" />
122 </junit>
123
124 <junit printsummary="yes" fork="no" haltonfailure="yes">
125 <classpath refid="path150Binding" />
126 <formatter type="plain" />
127 <test fork="yes" todir="target/unit-reports"
128 outfile="TEST-150BINDING"
129 name="org.slf4j.MissingSingletonMethodAssertionTest" />
130 </junit>
131
132 </target>
133
134
135 <target name="testMixed17">
136
137 <junit printsummary="yes" fork="no" haltonfailure="yes">
138 <classpath refid="pathMixed17" />
139 <formatter type="plain" />
140 <test fork="yes" todir="target/unit-reports"
141 outfile="TEST-MIXED-17"
142 name="org.slf4j.VersionMismatchAssertionTest" />
143 </junit>
144 </target>
145
146
147 <target name="testMismatch">
148
149 <junit printsummary="yes" fork="no" haltonfailure="yes">
150 <classpath refid="path1511API" />
151 <formatter type="plain" />
152 <test fork="yes" todir="target/unit-reports"
153 outfile="TEST-MISMATCH-1511API"
154 name="org.slf4j.VersionMismatchAssertionTest" />
155 </junit>
156
157
158 <junit printsummary="yes" fork="no" haltonfailure="yes">
159 <classpath refid="path1511Binding" />
160 <formatter type="plain" />
161 <test fork="yes" todir="target/unit-reports"
162 outfile="TEST-MISMATCH-1511Binding"
163 name="org.slf4j.VersionMismatchAssertionTest" />
164 </junit>
165
166 </target>
167
168 <target name="testMatch">
169 <junit printsummary="yes" fork="no" haltonfailure="yes">
170 <classpath refid="pathCurrent" />
171 <formatter type="plain" />
172 <test fork="yes" todir="target/unit-reports"
173 outfile="TEST-Match"
174 name="org.slf4j.CompatibilityAssertionTest" />
175 </junit>
176 </target>
177
178 <target name="testIncompatibleMultiBinding">
179 <junit printsummary="yes" fork="no" haltonfailure="yes">
180 <classpath refid="incompatibleMultiBinding" />
181 <formatter type="plain" />
182 <test fork="yes" todir="target/unit-reports"
183 outfile="TEST-IncompatibleMultiBinding"
184 name="org.slf4j.IncompatibleMultiBindingAssertionTest" />
185 </junit>
186 </target>
187
188 <target name="testMultiBinding">
189 <junit printsummary="yes" fork="no" haltonfailure="yes">
190 <classpath refid="multiBinding" />
191 <formatter type="plain" />
192 <test fork="yes" todir="target/unit-reports"
193 outfile="TEST-MultiBinding"
194 name="org.slf4j.MultiBindingAssertionTest" />
195 </junit>
196 </target>
197
198 <target name="testFuture_16Series">
199 <junit printsummary="yes" fork="no" haltonfailure="yes">
200 <classpath refid="binding166" />
201 <formatter type="plain" />
202 <test fork="yes" todir="target/unit-reports"
203 outfile="TEST-binding166"
204 name="org.slf4j.CompatibilityAssertionTest" />
205 </junit>
206
207
208 <junit printsummary="yes" fork="no" haltonfailure="yes">
209 <classpath refid="api166" />
210 <formatter type="plain" />
211 <test fork="yes" todir="target/unit-reports"
212 outfile="TEST-api166"
213 name="org.slf4j.CompatibilityAssertionTest" />
214 </junit>
215
216 </target>
217
218
219 <condition property="runFromWithinIntegrationModule">
220 <contains string="${user.dir}" substring="integration" />
221 </condition>
222
223 <target name="setPathToPolicy_FromTop" unless="runFromWithinIntegrationModule">
224 <echo>setPathToPolicy_FromTop</echo>
225 <property name="path_to_policy" value="file:./integration/src/policy/java-under-ant.policy"/>
226 </target>
227
228 <target name="setPathToPolicy_FromIntegration" if="runFromWithinIntegrationModule">
229 <echo>setPathToPolicy_FromInegration </echo>
230 <property name="path_to_policy" value="file:./src/policy/java-under-ant.policy"/>
231 </target>
232
233
234 <target name="testActiveSecurityManager" depends="setPathToPolicy_FromTop, setPathToPolicy_FromIntegration">
235 <junit printsummary="yes" fork="no" haltonfailure="yes">
236 <jvmarg value="-Djava.security.manager"/>
237 <jvmarg value="-Djava.security.policy=${path_to_policy}"/>
238 <jvmarg value="-Dslf4j.detectLoggerNameMismatch=true"/>
239 <classpath refid="pathCurrent" />
240 <formatter type="plain" />
241 <test fork="yes" todir="target/unit-reports"
242 outfile="TEST-SecurityManager"
243 name="org.slf4j.issues.Issue324Test" />
244 </junit>
245 </target>
246
0 <project name="integration" default="testAll" basedir=".">
1
2 <!--
3 This build file is usually run indirectly via Maven.
4
5 When running this build file through Ant directly, you must
6 define the currentVersion property on the command line, e.g.:
7
8 ant -DcurrentVersion=1.5.4-SNAPSHOT
9 -->
10
11 <echo message="compile classpath: ${compile_classpath}" />
12 <echo message="runtime classpath: ${runtime_classpath}" />
13 <echo message="test classpath: ${test_classpath}" />
14 <echo message="plugin classpath: ${plugin_classpath}" />
15 <echo message="basedir: ${basedir}" />
16
17
18 <!--<property name="path_to_policy" value="file:./integration/src/policy/java-under-ant.policy"/>-->
19
20
21 <path id="path142Binding">
22 <pathelement location="target/test-classes/" />
23 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
24 <pathelement location="./lib/slf4j-simple-1.4.2.jar" />
25 </path >
26
27 <path id="path150Binding">
28 <pathelement location="target/test-classes/" />
29 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
30 <pathelement location="./lib/slf4j-simple-1.5.0.jar" />
31 </path >
32
33 <path id="path1511API">
34 <pathelement location="target/test-classes/" />
35 <pathelement location="./lib/slf4j-api-1.5.11.jar" />
36 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
37 </path >
38
39 <path id="path1511Binding">
40 <pathelement location="target/test-classes/" />
41 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
42 <pathelement location="./lib/slf4j-simple-1.5.11.jar" />
43 </path >
44
45 <!--<path id="pathIncompatible">
46 <pathelement location="target/test-classes/" />
47 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
48 <pathelement location="./lib/slf4j-simple-INCOMPATIBLE.jar" />
49 </path >
50 -->
51
52 <path id="pathCurrent">
53 <pathelement location="target/test-classes/" />
54 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
55 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
56 </path >
57
58
59 <path id="incompatibleMultiBinding">
60 <pathelement location="target/test-classes/" />
61 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
62 <pathelement location="./lib/slf4j-simple-1.5.0.jar" />
63 <pathelement location="./lib/slf4j-nop-1.5.6.jar" />
64 </path >
65
66 <path id="multiBinding">
67 <pathelement location="target/test-classes/" />
68 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
69 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
70 <pathelement location="../slf4j-nop/target/slf4j-nop-${currentVersion}.jar" />
71 </path >
72
73 <path id="binding166">
74 <pathelement location="target/test-classes/" />
75 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
76 <pathelement location="./lib/slf4j-simple-1.6.6.jar" />
77 </path >
78
79 <path id="binding2099">
80 <pathelement location="target/test-classes/" />
81 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
82 <pathelement location="./lib/slf4j-simple-2.0.99.jar" />
83 </path >
84
85
86 <path id="api166">
87 <pathelement location="target/test-classes/" />
88 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
89 <pathelement location="./lib/slf4j-api-1.6.6.jar" />
90 </path >
91
92
93 <!-- this is really very ugly, but it's the only way to circumvent
94 http://jira.codehaus.org/browse/MANTRUN-95
95 -->
96 <taskdef name="junit" classpath="${plugin_classpath};${compile_classpath}"
97 classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTask" />
98
99 <target name="init">
100 <mkdir dir="target/unit-reports" />
101 </target>
102
103 <target name="testAll" depends="init,
104 testMissingSingletonMethod,
105 testMismatch,
106 testMatch,
107 testMultiBinding,
108 testIncompatibleMultiBinding,
109 testFuture_16Series,
110 testActiveSecurityManager">
111 </target>
112
113
114 <target name="testMissingSingletonMethod">
115
116 <junit printsummary="yes" fork="no" haltonfailure="yes">
117 <classpath refid="path142Binding" />
118 <formatter type="plain" />
119 <test fork="yes" todir="target/unit-reports"
120 outfile="TEST-142BININDING"
121 name="org.slf4j.MissingSingletonMethodAssertionTest" />
122 </junit>
123
124 <junit printsummary="yes" fork="no" haltonfailure="yes">
125 <classpath refid="path150Binding" />
126 <formatter type="plain" />
127 <test fork="yes" todir="target/unit-reports"
128 outfile="TEST-150BINDING"
129 name="org.slf4j.MissingSingletonMethodAssertionTest" />
130 </junit>
131
132 </target>
133
134
135 <target name="testMixed17">
136
137 <junit printsummary="yes" fork="no" haltonfailure="yes">
138 <classpath refid="pathMixed17" />
139 <formatter type="plain" />
140 <test fork="yes" todir="target/unit-reports"
141 outfile="TEST-MIXED-17"
142 name="org.slf4j.VersionMismatchAssertionTest" />
143 </junit>
144 </target>
145
146
147 <target name="testMismatch">
148
149 <junit printsummary="yes" fork="no" haltonfailure="yes">
150 <classpath refid="path1511API" />
151 <formatter type="plain" />
152 <test fork="yes" todir="target/unit-reports"
153 outfile="TEST-MISMATCH-1511API"
154 name="org.slf4j.VersionMismatchAssertionTest" />
155 </junit>
156
157
158 <junit printsummary="yes" fork="no" haltonfailure="yes">
159 <classpath refid="path1511Binding" />
160 <formatter type="plain" />
161 <test fork="yes" todir="target/unit-reports"
162 outfile="TEST-MISMATCH-1511Binding"
163 name="org.slf4j.VersionMismatchAssertionTest" />
164 </junit>
165
166 </target>
167
168 <target name="testMatch">
169 <junit printsummary="yes" fork="no" haltonfailure="yes">
170 <classpath refid="pathCurrent" />
171 <formatter type="plain" />
172 <test fork="yes" todir="target/unit-reports"
173 outfile="TEST-Match"
174 name="org.slf4j.CompatibilityAssertionTest" />
175 </junit>
176 </target>
177
178 <target name="testIncompatibleMultiBinding">
179 <junit printsummary="yes" fork="no" haltonfailure="yes">
180 <classpath refid="incompatibleMultiBinding" />
181 <formatter type="plain" />
182 <test fork="yes" todir="target/unit-reports"
183 outfile="TEST-IncompatibleMultiBinding"
184 name="org.slf4j.IncompatibleMultiBindingAssertionTest" />
185 </junit>
186 </target>
187
188 <target name="testMultiBinding">
189 <junit printsummary="yes" fork="no" haltonfailure="yes">
190 <classpath refid="multiBinding" />
191 <formatter type="plain" />
192 <test fork="yes" todir="target/unit-reports"
193 outfile="TEST-MultiBinding"
194 name="org.slf4j.MultiBindingAssertionTest" />
195 </junit>
196 </target>
197
198 <target name="testFuture_16Series">
199 <junit printsummary="yes" fork="no" haltonfailure="yes">
200 <classpath refid="binding166" />
201 <formatter type="plain" />
202 <test fork="yes" todir="target/unit-reports"
203 outfile="TEST-binding166"
204 name="org.slf4j.CompatibilityAssertionTest" />
205 </junit>
206
207
208 <junit printsummary="yes" fork="no" haltonfailure="yes">
209 <classpath refid="api166" />
210 <formatter type="plain" />
211 <test fork="yes" todir="target/unit-reports"
212 outfile="TEST-api166"
213 name="org.slf4j.CompatibilityAssertionTest" />
214 </junit>
215
216 </target>
217
218
219 <condition property="runFromWithinIntegrationModule">
220 <contains string="${user.dir}" substring="integration" />
221 </condition>
222
223 <target name="setPathToPolicy_FromTop" unless="runFromWithinIntegrationModule">
224 <echo>setPathToPolicy_FromTop</echo>
225 <property name="path_to_policy" value="file:./integration/src/policy/java-under-ant.policy"/>
226 </target>
227
228 <target name="setPathToPolicy_FromIntegration" if="runFromWithinIntegrationModule">
229 <echo>setPathToPolicy_FromInegration </echo>
230 <property name="path_to_policy" value="file:./src/policy/java-under-ant.policy"/>
231 </target>
232
233
234 <target name="testActiveSecurityManager" depends="setPathToPolicy_FromTop, setPathToPolicy_FromIntegration">
235 <junit printsummary="yes" fork="no" haltonfailure="yes">
236 <jvmarg value="-Djava.security.manager"/>
237 <jvmarg value="-Djava.security.policy=${path_to_policy}"/>
238 <jvmarg value="-Dslf4j.detectLoggerNameMismatch=true"/>
239 <classpath refid="pathCurrent" />
240 <formatter type="plain" />
241 <test fork="yes" todir="target/unit-reports"
242 outfile="TEST-SecurityManager"
243 name="org.slf4j.issues.Issue324Test" />
244 </junit>
245 </target>
246
247247 </project>
0 <project name="osgi-test" default="testAll">
1
2 <!--
3 This build file is usually run indirectly via Maven.
4
5 When running this build file through Ant directly, you must
6 define the currentVersion property on the command line, e.g.:
7
8 ant -DcurrentVersion=1.5.4-SNAPSHOT
9 -->
10
11 <echo message="compile classpath: ${currentVersion}" />
12 <echo message="test classpath: ${test_classpath}" />
13 <echo message="basedir: ${basedir}" />
14
15 <property name="iBundleJar" value="target/iBundle.jar"/>
16 <property name="bundlesDir" value="bundle"/>
17
18
19 <!-- this is really very ugly, but it's the only way to circumvent
20 http://jira.codehaus.org/browse/MANTRUN-95
21 -->
22 <taskdef name="junit" classpath="${test_classpath}"
23 classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTask" />
24
25 <path id="minimal">
26 <pathelement location="target/test-classes/" />
27 </path >
28
29 <target name="init">
30 <mkdir dir="target/unit-reports" />
31 </target>
32
33 <target name="createIBundle">
34 <mkdir dir="${bundlesDir}"/>
35 <jar destFile="${iBundleJar}"
36 manifest="src/IBUNDLE-META-INF/MANIFEST.MF"
37 basedir="target/test-classes/"
38 includes="integrator/**.class"/>
39
40 </target>
41
42 <target name="testAll" depends="init, createIBundle, nop, simple, jdk14">
43 </target>
44
45
46 <macrodef name="prepareOSGiHarness">
47 <attribute name="binding"/>
48 <sequential>
49 <delete>
50 <fileset dir="${bundlesDir}" includes="*.jar"/>
51 </delete>
52 <copy file="${iBundleJar}" todir="${bundlesDir}"/>
53 <copy file="../slf4j-api/target/slf4j-api-${currentVersion}.jar" todir="${bundlesDir}"/>
54 <copy file="../slf4j-@{binding}/target/slf4j-@{binding}-${currentVersion}.jar" todir="${bundlesDir}"/>
55 <echo>value of t = @{t}</echo>
56 </sequential>
57 </macrodef>
58
59
60 <!-- for some reason if mvn is invoked from the parent directory, junit gets
61 invoked from the parent dir, which messes up theses tests. Hence, the
62 fork="yes" dir="${basedir}" -->
63
64 <target name="nop">
65 <prepareOSGiHarness binding="nop"/>
66 <junit printsummary="yes" fork="yes" dir="${basedir}" haltonfailure="yes">
67 <classpath path="${test_classpath}"/>
68 <formatter type="plain" />
69 <test fork="yes" todir="target/unit-reports" name="org.slf4j.test_osgi.BundleTest" />
70 </junit>
71 </target>
72
73 <target name="simple">
74 <prepareOSGiHarness binding="simple"/>
75 <junit printsummary="yes" fork="yes" dir="${basedir}" haltonfailure="yes">
76 <classpath path="${test_classpath}"/>
77 <formatter type="plain" />
78 <test fork="yes" todir="target/unit-reports" name="org.slf4j.test_osgi.BundleTest" />
79 </junit>
80 </target>
81
82 <target name="jdk14">
83 <prepareOSGiHarness binding="jdk14"/>
84 <junit printsummary="yes" fork="yes" dir="${basedir}" haltonfailure="yes">
85 <classpath path="${test_classpath}"/>
86 <formatter type="plain" />
87 <test fork="yes" todir="target/unit-reports" name="org.slf4j.test_osgi.BundleTest" />
88 </junit>
89 </target>
90
0 <project name="osgi-test" default="testAll">
1
2 <!--
3 This build file is usually run indirectly via Maven.
4
5 When running this build file through Ant directly, you must
6 define the currentVersion property on the command line, e.g.:
7
8 ant -DcurrentVersion=1.5.4-SNAPSHOT
9 -->
10
11 <echo message="compile classpath: ${currentVersion}" />
12 <echo message="test classpath: ${test_classpath}" />
13 <echo message="basedir: ${basedir}" />
14
15 <property name="iBundleJar" value="target/iBundle.jar"/>
16 <property name="bundlesDir" value="bundle"/>
17
18
19 <!-- this is really very ugly, but it's the only way to circumvent
20 http://jira.codehaus.org/browse/MANTRUN-95
21 -->
22 <taskdef name="junit" classpath="${test_classpath}"
23 classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTask" />
24
25 <path id="minimal">
26 <pathelement location="target/test-classes/" />
27 </path >
28
29 <target name="init">
30 <mkdir dir="target/unit-reports" />
31 </target>
32
33 <target name="createIBundle">
34 <mkdir dir="${bundlesDir}"/>
35 <jar destFile="${iBundleJar}"
36 manifest="src/IBUNDLE-META-INF/MANIFEST.MF"
37 basedir="target/test-classes/"
38 includes="integrator/**.class"/>
39
40 </target>
41
42 <target name="testAll" depends="init, createIBundle, nop, simple, jdk14">
43 </target>
44
45
46 <macrodef name="prepareOSGiHarness">
47 <attribute name="binding"/>
48 <sequential>
49 <delete>
50 <fileset dir="${bundlesDir}" includes="*.jar"/>
51 </delete>
52 <copy file="${iBundleJar}" todir="${bundlesDir}"/>
53 <copy file="../slf4j-api/target/slf4j-api-${currentVersion}.jar" todir="${bundlesDir}"/>
54 <copy file="../slf4j-@{binding}/target/slf4j-@{binding}-${currentVersion}.jar" todir="${bundlesDir}"/>
55 <echo>value of t = @{t}</echo>
56 </sequential>
57 </macrodef>
58
59
60 <!-- for some reason if mvn is invoked from the parent directory, junit gets
61 invoked from the parent dir, which messes up theses tests. Hence, the
62 fork="yes" dir="${basedir}" -->
63
64 <target name="nop">
65 <prepareOSGiHarness binding="nop"/>
66 <junit printsummary="yes" fork="yes" dir="${basedir}" haltonfailure="yes">
67 <classpath path="${test_classpath}"/>
68 <formatter type="plain" />
69 <test fork="yes" todir="target/unit-reports" name="org.slf4j.test_osgi.BundleTest" />
70 </junit>
71 </target>
72
73 <target name="simple">
74 <prepareOSGiHarness binding="simple"/>
75 <junit printsummary="yes" fork="yes" dir="${basedir}" haltonfailure="yes">
76 <classpath path="${test_classpath}"/>
77 <formatter type="plain" />
78 <test fork="yes" todir="target/unit-reports" name="org.slf4j.test_osgi.BundleTest" />
79 </junit>
80 </target>
81
82 <target name="jdk14">
83 <prepareOSGiHarness binding="jdk14"/>
84 <junit printsummary="yes" fork="yes" dir="${basedir}" haltonfailure="yes">
85 <classpath path="${test_classpath}"/>
86 <formatter type="plain" />
87 <test fork="yes" todir="target/unit-reports" name="org.slf4j.test_osgi.BundleTest" />
88 </junit>
89 </target>
90
9191 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>integration</artifactId>
13 <packaging>jar</packaging>
14 <name>SLF4J Integration tests</name>
15
16 <url>http://www.slf4j.org</url>
17 <description>SLF4J integration tests</description>
18
19 <dependencies>
20 <dependency>
21 <groupId>org.slf4j</groupId>
22 <artifactId>slf4j-api</artifactId>
23 </dependency>
24
25 <!-- declaration to circumvent http://jira.codehaus.org/browse/MANTRUN-95 -->
26 <dependency>
27 <groupId>junit</groupId>
28 <artifactId>junit</artifactId>
29 <version>3.8.1</version>
30 </dependency>
31 <!-- declaration to circumvent http://jira.codehaus.org/browse/MANTRUN-95 -->
32 <dependency>
33 <groupId>ant</groupId>
34 <artifactId>ant-junit</artifactId>
35 <version>1.6.5</version>
36 </dependency>
37
38 <!-- some test run Felix in hosted mode -->
39 <dependency>
40 <groupId>org.apache.felix</groupId>
41 <artifactId>org.apache.felix.main</artifactId>
42 <version>5.6.1</version>
43 <!--<version>2.0.2</version>-->
44 </dependency>
45 </dependencies>
46
47 <build>
48 <plugins>
49 <plugin>
50 <artifactId>maven-antrun-plugin</artifactId>
51 <version>1.2</version>
52 <dependencies>
53 <dependency>
54 <groupId>junit</groupId>
55 <artifactId>junit</artifactId>
56 <version>3.8.1</version>
57 </dependency>
58 <dependency>
59 <groupId>ant</groupId>
60 <artifactId>ant-junit</artifactId>
61 <version>1.6.5</version>
62 </dependency>
63 </dependencies>
64 <executions>
65 <execution>
66 <id>ant-test</id>
67 <phase>package</phase>
68 <configuration>
69 <tasks>
70 <property name="currentVersion" value="${project.version}"/>
71 <property name="compile_classpath" refid="maven.compile.classpath"/>
72 <property name="runtime_classpath" refid="maven.runtime.classpath"/>
73 <property name="test_classpath" refid="maven.test.classpath"/>
74 <property name="plugin_classpath" refid="maven.plugin.classpath"/>
75 <ant antfile="${basedir}/build.xml"/>
76 </tasks>
77 </configuration>
78 <goals>
79 <goal>run</goal>
80 </goals>
81 </execution>
82 <execution>
83 <id>ant-osgi-test</id>
84 <phase>package</phase>
85 <configuration>
86 <tasks>
87 <property name="currentVersion" value="${project.version}"/>
88 <property name="test_classpath" refid="maven.test.classpath"/>
89 <property name="basedir" value="${basedir}"/>
90 <ant antfile="${basedir}/osgi-build.xml"/>
91 </tasks>
92 </configuration>
93 <goals>
94 <goal>run</goal>
95 </goals>
96 </execution>
97
98 </executions>
99 </plugin>
100
101 <plugin>
102 <groupId>org.apache.maven.plugins</groupId>
103 <artifactId>maven-surefire-plugin</artifactId>
104 <configuration>
105 <forkMode>once</forkMode>
106 <reportFormat>plain</reportFormat>
107 <trimStackTrace>false</trimStackTrace>
108 <excludes>
109 <exclude>**/*Test.java</exclude>
110 </excludes>
111 </configuration>
112 </plugin>
113 </plugins>
114
115
116 </build>
117
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>integration</artifactId>
13 <packaging>jar</packaging>
14 <name>SLF4J Integration tests</name>
15
16 <url>http://www.slf4j.org</url>
17 <description>SLF4J integration tests</description>
18
19 <dependencies>
20 <dependency>
21 <groupId>org.slf4j</groupId>
22 <artifactId>slf4j-api</artifactId>
23 </dependency>
24
25 <!-- declaration to circumvent http://jira.codehaus.org/browse/MANTRUN-95 -->
26 <dependency>
27 <groupId>junit</groupId>
28 <artifactId>junit</artifactId>
29 <version>3.8.1</version>
30 </dependency>
31 <!-- declaration to circumvent http://jira.codehaus.org/browse/MANTRUN-95 -->
32 <dependency>
33 <groupId>ant</groupId>
34 <artifactId>ant-junit</artifactId>
35 <version>1.6.5</version>
36 </dependency>
37
38 <!-- some test run Felix in hosted mode -->
39 <dependency>
40 <groupId>org.apache.felix</groupId>
41 <artifactId>org.apache.felix.main</artifactId>
42 <version>5.6.1</version>
43 <!--<version>2.0.2</version>-->
44 </dependency>
45 </dependencies>
46
47 <build>
48 <plugins>
49 <plugin>
50 <artifactId>maven-antrun-plugin</artifactId>
51 <version>1.2</version>
52 <dependencies>
53 <dependency>
54 <groupId>junit</groupId>
55 <artifactId>junit</artifactId>
56 <version>3.8.1</version>
57 </dependency>
58 <dependency>
59 <groupId>ant</groupId>
60 <artifactId>ant-junit</artifactId>
61 <version>1.6.5</version>
62 </dependency>
63 </dependencies>
64 <executions>
65 <execution>
66 <id>ant-test</id>
67 <phase>package</phase>
68 <configuration>
69 <tasks>
70 <property name="currentVersion" value="${project.version}"/>
71 <property name="compile_classpath" refid="maven.compile.classpath"/>
72 <property name="runtime_classpath" refid="maven.runtime.classpath"/>
73 <property name="test_classpath" refid="maven.test.classpath"/>
74 <property name="plugin_classpath" refid="maven.plugin.classpath"/>
75 <ant antfile="${basedir}/build.xml"/>
76 </tasks>
77 </configuration>
78 <goals>
79 <goal>run</goal>
80 </goals>
81 </execution>
82 <execution>
83 <id>ant-osgi-test</id>
84 <phase>package</phase>
85 <configuration>
86 <tasks>
87 <property name="currentVersion" value="${project.version}"/>
88 <property name="test_classpath" refid="maven.test.classpath"/>
89 <property name="basedir" value="${basedir}"/>
90 <ant antfile="${basedir}/osgi-build.xml"/>
91 </tasks>
92 </configuration>
93 <goals>
94 <goal>run</goal>
95 </goals>
96 </execution>
97
98 </executions>
99 </plugin>
100
101 <plugin>
102 <groupId>org.apache.maven.plugins</groupId>
103 <artifactId>maven-surefire-plugin</artifactId>
104 <configuration>
105 <forkMode>once</forkMode>
106 <reportFormat>plain</reportFormat>
107 <trimStackTrace>false</trimStackTrace>
108 <excludes>
109 <exclude>**/*Test.java</exclude>
110 </excludes>
111 </configuration>
112 </plugin>
113 </plugins>
114
115
116 </build>
117
118118 </project>
0 Manifest-Version: 1.0
1 Archiver-Version: Plexus Archiver
2 Created-By: Apache Maven
3 Built-By: ceki
4 Build-Jdk: 1.6.0_16
5 Bundle-Description: iBundle
6 Bundle-Version: 0.1
7 Bundle-Activator: integrator.Activator
8 Implementation-Title: iBundle
9 Bundle-ManifestVersion: 2
10 Bundle-SymbolicName: iBundle
11 Bundle-Name: abundle
12 Bundle-RequiredExecutionEnvironment: J2SE-1.5
13 Export-Package: apack
0 Manifest-Version: 1.0
1 Archiver-Version: Plexus Archiver
2 Created-By: Apache Maven
3 Built-By: ceki
4 Build-Jdk: 1.6.0_16
5 Bundle-Description: iBundle
6 Bundle-Version: 0.1
7 Bundle-Activator: integrator.Activator
8 Implementation-Title: iBundle
9 Bundle-ManifestVersion: 2
10 Bundle-SymbolicName: iBundle
11 Bundle-Name: abundle
12 Bundle-RequiredExecutionEnvironment: J2SE-1.5
13 Export-Package: apack
1414 Import-Package: org.osgi.framework, org.slf4j;version=1.5
0
1 grant {
2
3 // note that java.lang.RuntimePermission createSecurityManager is NOT granted
4
5 permission java.util.PropertyPermission "user.dir", "read";
6 permission java.util.PropertyPermission "*", "read";
7
8 permission java.net.SocketPermission "*", "connect,resolve";
0
1 grant {
2
3 // note that java.lang.RuntimePermission createSecurityManager is NOT granted
4
5 permission java.util.PropertyPermission "user.dir", "read";
6 permission java.util.PropertyPermission "*", "read";
7
8 permission java.net.SocketPermission "*", "connect,resolve";
99 };
0
1 grant {
2
3 // note that java.lang.RuntimePermission createSecurityManager is NOT granted
4
5 permission java.util.PropertyPermission "user.dir", "read";
6
7 // permissions required for Ant's Junit runner
8 permission java.util.PropertyPermission "*", "read, write";
9 permission java.io.FilePermission "./-", "read";
10 permission java.io.FilePermission "./-", "write";
11 permission java.lang.RuntimePermission "setIO";
0
1 grant {
2
3 // note that java.lang.RuntimePermission createSecurityManager is NOT granted
4
5 permission java.util.PropertyPermission "user.dir", "read";
6
7 // permissions required for Ant's Junit runner
8 permission java.util.PropertyPermission "*", "read, write";
9 permission java.io.FilePermission "./-", "read";
10 permission java.io.FilePermission "./-", "write";
11 permission java.lang.RuntimePermission "setIO";
1212 };
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package integrator;
25
26 import org.osgi.framework.Bundle;
27 import org.osgi.framework.BundleActivator;
28 import org.osgi.framework.BundleContext;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33 * A BundleActivator which invokes slf4j loggers
34 * @author Ceki G&uuml;lc&uuml;
35 *
36 */
37 public class Activator implements BundleActivator {
38
39 private BundleContext m_context = null;
40
41 public void start(BundleContext context) {
42 Logger logger = LoggerFactory.getLogger(this.getClass());
43 logger.info("Activator.start()");
44 m_context = context;
45 }
46
47 public void stop(BundleContext context) {
48 m_context = null;
49 Logger logger = LoggerFactory.getLogger(this.getClass());
50 logger.info("Activator.stop");
51 }
52
53 public Bundle[] getBundles() {
54 if (m_context != null) {
55 return m_context.getBundles();
56 }
57 return null;
58 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package integrator;
25
26 import org.osgi.framework.Bundle;
27 import org.osgi.framework.BundleActivator;
28 import org.osgi.framework.BundleContext;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33 * A BundleActivator which invokes slf4j loggers
34 * @author Ceki G&uuml;lc&uuml;
35 *
36 */
37 public class Activator implements BundleActivator {
38
39 private BundleContext m_context = null;
40
41 public void start(BundleContext context) {
42 Logger logger = LoggerFactory.getLogger(this.getClass());
43 logger.info("Activator.start()");
44 m_context = context;
45 }
46
47 public void stop(BundleContext context) {
48 m_context = null;
49 Logger logger = LoggerFactory.getLogger(this.getClass());
50 logger.info("Activator.stop");
51 }
52
53 public Bundle[] getBundles() {
54 if (m_context != null) {
55 return m_context.getBundles();
56 }
57 return null;
58 }
5959 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j;
26
27 import java.io.PrintStream;
28 import java.util.Random;
29
30 import junit.framework.TestCase;
31
32 public class CompatibilityAssertionTest extends TestCase {
33
34 StringPrintStream sps = new StringPrintStream(System.err);
35 PrintStream old = System.err;
36 int diff = 1024 + new Random().nextInt(10000);
37
38 public CompatibilityAssertionTest(String name) {
39 super(name);
40 }
41
42 protected void setUp() throws Exception {
43 super.setUp();
44 System.setErr(sps);
45 }
46
47 protected void tearDown() throws Exception {
48 super.tearDown();
49 System.setErr(old);
50 }
51
52 public void test() throws Exception {
53 Logger logger = LoggerFactory.getLogger(this.getClass());
54 String msg = "hello world " + diff;
55 logger.info(msg);
56 assertEquals(1, sps.stringList.size());
57 String s0 = (String) sps.stringList.get(0);
58 assertTrue(s0.contains(msg));
59 }
60 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j;
26
27 import java.io.PrintStream;
28 import java.util.Random;
29
30 import junit.framework.TestCase;
31
32 public class CompatibilityAssertionTest extends TestCase {
33
34 StringPrintStream sps = new StringPrintStream(System.err);
35 PrintStream old = System.err;
36 int diff = 1024 + new Random().nextInt(10000);
37
38 public CompatibilityAssertionTest(String name) {
39 super(name);
40 }
41
42 protected void setUp() throws Exception {
43 super.setUp();
44 System.setErr(sps);
45 }
46
47 protected void tearDown() throws Exception {
48 super.tearDown();
49 System.setErr(old);
50 }
51
52 public void test() throws Exception {
53 Logger logger = LoggerFactory.getLogger(this.getClass());
54 String msg = "hello world " + diff;
55 logger.info(msg);
56 assertEquals(1, sps.stringList.size());
57 String s0 = (String) sps.stringList.get(0);
58 assertTrue(s0.contains(msg));
59 }
60 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.List;
28 import java.util.Random;
29
30 import junit.framework.TestCase;
31
32 public class IncompatibleMultiBindingAssertionTest extends TestCase {
33
34 StringPrintStream sps = new StringPrintStream(System.err);
35 PrintStream old = System.err;
36 int diff = 1024 + new Random().nextInt(10000);
37
38 public IncompatibleMultiBindingAssertionTest(String name) {
39 super(name);
40 }
41
42 protected void setUp() throws Exception {
43 super.setUp();
44 System.setErr(sps);
45 }
46
47 protected void tearDown() throws Exception {
48 super.tearDown();
49 System.setErr(old);
50 }
51
52 public void test() throws Exception {
53 try {
54 Logger logger = LoggerFactory.getLogger(this.getClass());
55 String msg = "hello world " + diff;
56 logger.info(msg);
57 fail("was expecting NoSuchMethodError");
58 } catch (NoSuchMethodError e) {
59 }
60 List<String> list = sps.stringList;
61 assertMsgContains(list, 0, "Class path contains multiple SLF4J bindings.");
62 assertMsgContains(list, 1, "Found binding in");
63 assertMsgContains(list, 2, "Found binding in");
64 assertMsgContains(list, 3, "See http://www.slf4j.org/codes.html");
65 assertMsgContains(list, 4, "slf4j-api 1.6.x (or later) is incompatible with this binding");
66 assertMsgContains(list, 5, "Your binding is version 1.5.5 or earlier.");
67
68 }
69
70 void assertMsgContains(List<String> strList, int index, String msg) {
71 assertTrue(((String) strList.get(index)).contains(msg));
72 }
73 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.List;
28 import java.util.Random;
29
30 import junit.framework.TestCase;
31
32 public class IncompatibleMultiBindingAssertionTest extends TestCase {
33
34 StringPrintStream sps = new StringPrintStream(System.err);
35 PrintStream old = System.err;
36 int diff = 1024 + new Random().nextInt(10000);
37
38 public IncompatibleMultiBindingAssertionTest(String name) {
39 super(name);
40 }
41
42 protected void setUp() throws Exception {
43 super.setUp();
44 System.setErr(sps);
45 }
46
47 protected void tearDown() throws Exception {
48 super.tearDown();
49 System.setErr(old);
50 }
51
52 public void test() throws Exception {
53 try {
54 Logger logger = LoggerFactory.getLogger(this.getClass());
55 String msg = "hello world " + diff;
56 logger.info(msg);
57 fail("was expecting NoSuchMethodError");
58 } catch (NoSuchMethodError e) {
59 }
60 List<String> list = sps.stringList;
61 assertMsgContains(list, 0, "Class path contains multiple SLF4J bindings.");
62 assertMsgContains(list, 1, "Found binding in");
63 assertMsgContains(list, 2, "Found binding in");
64 assertMsgContains(list, 3, "See http://www.slf4j.org/codes.html");
65 assertMsgContains(list, 4, "slf4j-api 1.6.x (or later) is incompatible with this binding");
66 assertMsgContains(list, 5, "Your binding is version 1.5.5 or earlier.");
67
68 }
69
70 void assertMsgContains(List<String> strList, int index, String msg) {
71 assertTrue(((String) strList.get(index)).contains(msg));
72 }
73 }
0 /**
1 * Copyright (c) 2004-2016 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.Random;
28
29 import junit.framework.TestCase;
30
31 public class MissingSingletonMethodAssertionTest extends TestCase {
32
33 StringPrintStream sps = new StringPrintStream(System.err);
34 PrintStream old = System.err;
35 int diff = 1024 + new Random().nextInt(10000);
36
37 public MissingSingletonMethodAssertionTest(String name) {
38 super(name);
39 }
40
41 protected void setUp() throws Exception {
42 super.setUp();
43 System.setErr(sps);
44 }
45
46 protected void tearDown() throws Exception {
47 super.tearDown();
48 System.setErr(old);
49 }
50
51 public void test() throws Exception {
52 try {
53 Logger logger = LoggerFactory.getLogger(this.getClass());
54 String msg = "hello world " + diff;
55 logger.info(msg);
56 fail("NoSuchMethodError expected");
57 } catch (NoSuchMethodError e) {
58 }
59
60 int lineCount = sps.stringList.size();
61 assertTrue("number of lines should be 3 but was " + lineCount, lineCount == 3);
62
63 // expected output:
64 // SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.
65 // SLF4J: Your binding is version 1.4.x or earlier.
66 // SLF4J: Upgrade your binding to version 1.6.x. or 2.0.x
67
68 {
69 String s = (String) sps.stringList.get(0);
70 assertTrue(s.contains("SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding."));
71 }
72 {
73 String s = (String) sps.stringList.get(1);
74 assertTrue(s.contains("SLF4J: Your binding is version 1.5.5 or earlier."));
75 }
76 {
77 String s = (String) sps.stringList.get(2);
78 assertTrue(s.contains("SLF4J: Upgrade your binding to version 1.6.x."));
79 }
80
81 }
82 }
0 /**
1 * Copyright (c) 2004-2016 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.Random;
28
29 import junit.framework.TestCase;
30
31 public class MissingSingletonMethodAssertionTest extends TestCase {
32
33 StringPrintStream sps = new StringPrintStream(System.err);
34 PrintStream old = System.err;
35 int diff = 1024 + new Random().nextInt(10000);
36
37 public MissingSingletonMethodAssertionTest(String name) {
38 super(name);
39 }
40
41 protected void setUp() throws Exception {
42 super.setUp();
43 System.setErr(sps);
44 }
45
46 protected void tearDown() throws Exception {
47 super.tearDown();
48 System.setErr(old);
49 }
50
51 public void test() throws Exception {
52 try {
53 Logger logger = LoggerFactory.getLogger(this.getClass());
54 String msg = "hello world " + diff;
55 logger.info(msg);
56 fail("NoSuchMethodError expected");
57 } catch (NoSuchMethodError e) {
58 }
59
60 int lineCount = sps.stringList.size();
61 assertTrue("number of lines should be 3 but was " + lineCount, lineCount == 3);
62
63 // expected output:
64 // SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.
65 // SLF4J: Your binding is version 1.4.x or earlier.
66 // SLF4J: Upgrade your binding to version 1.6.x. or 2.0.x
67
68 {
69 String s = (String) sps.stringList.get(0);
70 assertTrue(s.contains("SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding."));
71 }
72 {
73 String s = (String) sps.stringList.get(1);
74 assertTrue(s.contains("SLF4J: Your binding is version 1.5.5 or earlier."));
75 }
76 {
77 String s = (String) sps.stringList.get(2);
78 assertTrue(s.contains("SLF4J: Upgrade your binding to version 1.6.x."));
79 }
80
81 }
82 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.List;
28 import java.util.Random;
29
30 import junit.framework.TestCase;
31
32 public class MultiBindingAssertionTest extends TestCase {
33
34 StringPrintStream sps = new StringPrintStream(System.err);
35 PrintStream old = System.err;
36 int diff = 1024 + new Random().nextInt(10000);
37
38 public MultiBindingAssertionTest(String name) {
39 super(name);
40 }
41
42 protected void setUp() throws Exception {
43 super.setUp();
44 System.setErr(sps);
45 }
46
47 protected void tearDown() throws Exception {
48 super.tearDown();
49 System.setErr(old);
50 }
51
52 public void test() throws Exception {
53 Logger logger = LoggerFactory.getLogger(this.getClass());
54 String msg = "hello world " + diff;
55 logger.info(msg);
56 List<String> list = sps.stringList;
57 assertMsgContains(list, 0, "Class path contains multiple SLF4J bindings.");
58 assertMsgContains(list, 1, "Found binding in");
59 assertMsgContains(list, 2, "Found binding in");
60 assertMsgContains(list, 3, "See http://www.slf4j.org/codes.html");
61 assertMsgContains(list, 4, "Actual binding is of type [");
62 }
63
64 void assertMsgContains(List<String> strList, int index, String msg) {
65 assertTrue(((String) strList.get(index)).contains(msg));
66 }
67 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.List;
28 import java.util.Random;
29
30 import junit.framework.TestCase;
31
32 public class MultiBindingAssertionTest extends TestCase {
33
34 StringPrintStream sps = new StringPrintStream(System.err);
35 PrintStream old = System.err;
36 int diff = 1024 + new Random().nextInt(10000);
37
38 public MultiBindingAssertionTest(String name) {
39 super(name);
40 }
41
42 protected void setUp() throws Exception {
43 super.setUp();
44 System.setErr(sps);
45 }
46
47 protected void tearDown() throws Exception {
48 super.tearDown();
49 System.setErr(old);
50 }
51
52 public void test() throws Exception {
53 Logger logger = LoggerFactory.getLogger(this.getClass());
54 String msg = "hello world " + diff;
55 logger.info(msg);
56 List<String> list = sps.stringList;
57 assertMsgContains(list, 0, "Class path contains multiple SLF4J bindings.");
58 assertMsgContains(list, 1, "Found binding in");
59 assertMsgContains(list, 2, "Found binding in");
60 assertMsgContains(list, 3, "See http://www.slf4j.org/codes.html");
61 assertMsgContains(list, 4, "Actual binding is of type [");
62 }
63
64 void assertMsgContains(List<String> strList, int index, String msg) {
65 assertTrue(((String) strList.get(index)).contains(msg));
66 }
67 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.ArrayList;
28 import java.util.List;
29
30 public class StringPrintStream extends PrintStream {
31
32 public static final String LINE_SEP = System.getProperty("line.separator");
33 PrintStream other;
34 List<String> stringList = new ArrayList<String>();
35
36 public StringPrintStream(PrintStream ps) {
37 super(ps);
38 other = ps;
39 }
40
41 public void print(String s) {
42 other.print(s);
43 stringList.add(s);
44 }
45
46 public void println(String s) {
47 other.println(s);
48 stringList.add(s);
49 }
50
51 public void println(Object o) {
52 other.println(o);
53 stringList.add(o.toString());
54 }
55 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.ArrayList;
28 import java.util.List;
29
30 public class StringPrintStream extends PrintStream {
31
32 public static final String LINE_SEP = System.getProperty("line.separator");
33 PrintStream other;
34 List<String> stringList = new ArrayList<String>();
35
36 public StringPrintStream(PrintStream ps) {
37 super(ps);
38 other = ps;
39 }
40
41 public void print(String s) {
42 other.print(s);
43 stringList.add(s);
44 }
45
46 public void println(String s) {
47 other.println(s);
48 stringList.add(s);
49 }
50
51 public void println(Object o) {
52 other.println(o);
53 stringList.add(o.toString());
54 }
55 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.Random;
28
29 import junit.framework.TestCase;
30
31 public class VersionMismatchAssertionTest extends TestCase {
32
33 StringPrintStream sps = new StringPrintStream(System.err);
34 PrintStream old = System.err;
35 int diff = 1024 + new Random().nextInt(10000);
36
37 public VersionMismatchAssertionTest(String name) {
38 super(name);
39 }
40
41 protected void setUp() throws Exception {
42 super.setUp();
43 System.setErr(sps);
44 }
45
46 protected void tearDown() throws Exception {
47 super.tearDown();
48 System.setErr(old);
49 }
50
51 public void test() throws Exception {
52 Logger logger = LoggerFactory.getLogger(this.getClass());
53 String msg = "hello world " + diff;
54 logger.info(msg);
55
56 String s0 = (String) sps.stringList.get(0);
57 assertTrue(s0.matches("SLF4J: The requested version .* by your slf4j binding is not compatible with.*"));
58
59 String s1 = (String) sps.stringList.get(1);
60 assertTrue(s1.contains(LoggerFactory.VERSION_MISMATCH));
61
62 String s2 = (String) sps.stringList.get(2);
63 assertTrue(s2.contains(msg));
64
65 }
66 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.Random;
28
29 import junit.framework.TestCase;
30
31 public class VersionMismatchAssertionTest extends TestCase {
32
33 StringPrintStream sps = new StringPrintStream(System.err);
34 PrintStream old = System.err;
35 int diff = 1024 + new Random().nextInt(10000);
36
37 public VersionMismatchAssertionTest(String name) {
38 super(name);
39 }
40
41 protected void setUp() throws Exception {
42 super.setUp();
43 System.setErr(sps);
44 }
45
46 protected void tearDown() throws Exception {
47 super.tearDown();
48 System.setErr(old);
49 }
50
51 public void test() throws Exception {
52 Logger logger = LoggerFactory.getLogger(this.getClass());
53 String msg = "hello world " + diff;
54 logger.info(msg);
55
56 String s0 = (String) sps.stringList.get(0);
57 assertTrue(s0.matches("SLF4J: The requested version .* by your slf4j binding is not compatible with.*"));
58
59 String s1 = (String) sps.stringList.get(1);
60 assertTrue(s1.contains(LoggerFactory.VERSION_MISMATCH));
61
62 String s2 = (String) sps.stringList.get(2);
63 assertTrue(s2.contains(msg));
64
65 }
66 }
0 package org.slf4j.issues;
1
2 import org.slf4j.Logger;
3 import org.slf4j.LoggerFactory;
4
5 import junit.framework.TestCase;
6
7 public class Issue324Test extends TestCase {
8
9 public void testLoggerCreationInPresenseOfSecurityManager() {
10 String currentDir = System.getProperty("user.dir");
11 System.out.println("currentDir:" + currentDir);
12 Logger logger = LoggerFactory.getLogger(Issue324Test.class);
13 logger.debug("hello");
14 }
15 }
0 package org.slf4j.issues;
1
2 import org.slf4j.Logger;
3 import org.slf4j.LoggerFactory;
4
5 import junit.framework.TestCase;
6
7 public class Issue324Test extends TestCase {
8
9 public void testLoggerCreationInPresenseOfSecurityManager() {
10 String currentDir = System.getProperty("user.dir");
11 System.out.println("currentDir:" + currentDir);
12 Logger logger = LoggerFactory.getLogger(Issue324Test.class);
13 logger.debug("hello");
14 }
15 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.io.File;
27
28 import junit.framework.TestCase;
29
30 public class BundleTest extends TestCase {
31
32 FrameworkErrorListener fel = new FrameworkErrorListener();
33 CheckingBundleListener mbl = new CheckingBundleListener();
34
35 FelixHost felixHost = new FelixHost(fel, mbl);
36
37 protected void setUp() throws Exception {
38 super.setUp();
39 felixHost.doLaunch();
40 }
41
42 protected void tearDown() throws Exception {
43 super.tearDown();
44 felixHost.stop();
45 }
46
47 public void testSmoke() {
48 System.out.println("===========" + new File(".").getAbsolutePath());
49 mbl.dumpAll();
50 // check that the bundle was installed
51 assertTrue(mbl.exists("iBundle"));
52 if (fel.errorList.size() != 0) {
53 fel.dumpAll();
54 }
55 // check that no errors occured
56 assertEquals(0, fel.errorList.size());
57 }
58 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.io.File;
27
28 import junit.framework.TestCase;
29
30 public class BundleTest extends TestCase {
31
32 FrameworkErrorListener fel = new FrameworkErrorListener();
33 CheckingBundleListener mbl = new CheckingBundleListener();
34
35 FelixHost felixHost = new FelixHost(fel, mbl);
36
37 protected void setUp() throws Exception {
38 super.setUp();
39 felixHost.doLaunch();
40 }
41
42 protected void tearDown() throws Exception {
43 super.tearDown();
44 felixHost.stop();
45 }
46
47 public void testSmoke() {
48 System.out.println("===========" + new File(".").getAbsolutePath());
49 mbl.dumpAll();
50 // check that the bundle was installed
51 assertTrue(mbl.exists("iBundle"));
52 if (fel.errorList.size() != 0) {
53 fel.dumpAll();
54 }
55 // check that no errors occured
56 assertEquals(0, fel.errorList.size());
57 }
58 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.osgi.framework.Bundle;
30 import org.osgi.framework.BundleEvent;
31 import org.osgi.framework.BundleListener;
32
33 public class CheckingBundleListener implements BundleListener {
34
35 List<BundleEvent> eventList = new ArrayList<BundleEvent>();
36
37 public void bundleChanged(BundleEvent be) {
38 eventList.add(be);
39 }
40
41 private void dump(BundleEvent be) {
42 System.out.println("BE:" + ", source " + be.getSource() + ", bundle=" + be.getBundle() + ", type=" + be.getType());
43
44 }
45
46 public void dumpAll() {
47 for (int i = 0; i < eventList.size(); i++) {
48 BundleEvent fe = (BundleEvent) eventList.get(i);
49 dump(fe);
50 }
51 }
52
53 boolean exists(String bundleName) {
54 for (int i = 0; i < eventList.size(); i++) {
55 BundleEvent fe = (BundleEvent) eventList.get(i);
56 Bundle b = fe.getBundle();
57 System.out.println("===[" + b + "]");
58 if (bundleName.equals(b.getSymbolicName())) {
59 return true;
60 }
61 }
62 return false;
63 }
64
65 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.osgi.framework.Bundle;
30 import org.osgi.framework.BundleEvent;
31 import org.osgi.framework.BundleListener;
32
33 public class CheckingBundleListener implements BundleListener {
34
35 List<BundleEvent> eventList = new ArrayList<BundleEvent>();
36
37 public void bundleChanged(BundleEvent be) {
38 eventList.add(be);
39 }
40
41 private void dump(BundleEvent be) {
42 System.out.println("BE:" + ", source " + be.getSource() + ", bundle=" + be.getBundle() + ", type=" + be.getType());
43
44 }
45
46 public void dumpAll() {
47 for (int i = 0; i < eventList.size(); i++) {
48 BundleEvent fe = (BundleEvent) eventList.get(i);
49 dump(fe);
50 }
51 }
52
53 boolean exists(String bundleName) {
54 for (int i = 0; i < eventList.size(); i++) {
55 BundleEvent fe = (BundleEvent) eventList.get(i);
56 Bundle b = fe.getBundle();
57 System.out.println("===[" + b + "]");
58 if (bundleName.equals(b.getSymbolicName())) {
59 return true;
60 }
61 }
62 return false;
63 }
64
65 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Properties;
29
30 import org.apache.felix.framework.Felix;
31 import org.apache.felix.framework.util.FelixConstants;
32 import org.apache.felix.framework.util.StringMap;
33 import org.apache.felix.main.AutoProcessor;
34 import org.osgi.framework.Bundle;
35 import org.osgi.framework.BundleContext;
36 import org.osgi.framework.BundleException;
37 import org.osgi.framework.Constants;
38
39 /**
40 * Runs a hosted version of Felix for testing purposes. Any bundle errors are
41 * reported via the FrameworkListener passed to the constructor.
42 *
43 * @author Ceki G&uuml;lc&uuml;
44 */
45 public class FelixHost {
46
47 private Felix felix = null;
48
49 Properties otherProps = new Properties();
50
51 final FrameworkErrorListener frameworkErrorListener;
52 final CheckingBundleListener myBundleListener;
53
54 public FelixHost(FrameworkErrorListener frameworkErrorListener, CheckingBundleListener myBundleListener) {
55 this.frameworkErrorListener = frameworkErrorListener;
56 this.myBundleListener = myBundleListener;
57 }
58
59 public void doLaunch() {
60 // Create a case-insensitive configuration property map.
61 StringMap configMap = new StringMap();
62 // Configure the Felix instance to be embedded.
63 // configMap.put(FelixConstants.EMBEDDED_EXECUTION_PROP, "true");
64 // Add core OSGi packages to be exported from the class path
65 // via the system bundle.
66 configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES, "org.osgi.framework; version=1.3.0," + "org.osgi.service.packageadmin; version=1.2.0,"
67 + "org.osgi.service.startlevel; version=1.0.0," + "org.osgi.service.url; version=1.0.0");
68
69 configMap.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
70
71 // Explicitly specify the directory to use for caching bundles.
72 // configMap.put(BundleCache.CACHE_PROFILE_DIR_PROP, "cache");
73
74 try {
75 // Create host activator;
76
77 List<Object> list = new ArrayList<Object>();
78
79 // list.add(new HostActivator());
80 configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.xml.sax, org.xml.sax.helpers, javax.xml.parsers, javax.naming");
81 configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
82 configMap.put("felix.log.level", "4");
83
84 // Now create an instance of the framework with
85 // our configuration properties and activator.
86 felix = new Felix(configMap);
87 felix.init();
88
89 // otherProps.put(Constants.FRAMEWORK_STORAGE, "bundles");
90
91 otherProps.put(AutoProcessor.AUTO_DEPLOY_DIR_PROPERTY, AutoProcessor.AUTO_DEPLOY_DIR_VALUE);
92 otherProps.put(AutoProcessor.AUTO_DEPLOY_ACTION_PROPERTY, AutoProcessor.AUTO_DEPLOY_START_VALUE + "," + AutoProcessor.AUTO_DEPLOY_INSTALL_VALUE);
93
94 BundleContext felixBudleContext = felix.getBundleContext();
95
96 AutoProcessor.process(otherProps, felixBudleContext);
97 // listen to errors
98 felixBudleContext.addFrameworkListener(frameworkErrorListener);
99 felixBudleContext.addBundleListener(myBundleListener);
100 // Now start Felix instance.
101 felix.start();
102 System.out.println("felix started");
103
104 } catch (Exception ex) {
105 ex.printStackTrace();
106 }
107 }
108
109 public void stop() throws BundleException {
110 felix.stop();
111 }
112
113 public Bundle[] getInstalledBundles() {
114 // Use the system bundle activator to gain external
115 // access to the set of installed bundles.
116 return null;// m_activator.getBundles();
117 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Properties;
29
30 import org.apache.felix.framework.Felix;
31 import org.apache.felix.framework.util.FelixConstants;
32 import org.apache.felix.framework.util.StringMap;
33 import org.apache.felix.main.AutoProcessor;
34 import org.osgi.framework.Bundle;
35 import org.osgi.framework.BundleContext;
36 import org.osgi.framework.BundleException;
37 import org.osgi.framework.Constants;
38
39 /**
40 * Runs a hosted version of Felix for testing purposes. Any bundle errors are
41 * reported via the FrameworkListener passed to the constructor.
42 *
43 * @author Ceki G&uuml;lc&uuml;
44 */
45 public class FelixHost {
46
47 private Felix felix = null;
48
49 Properties otherProps = new Properties();
50
51 final FrameworkErrorListener frameworkErrorListener;
52 final CheckingBundleListener myBundleListener;
53
54 public FelixHost(FrameworkErrorListener frameworkErrorListener, CheckingBundleListener myBundleListener) {
55 this.frameworkErrorListener = frameworkErrorListener;
56 this.myBundleListener = myBundleListener;
57 }
58
59 public void doLaunch() {
60 // Create a case-insensitive configuration property map.
61 StringMap configMap = new StringMap();
62 // Configure the Felix instance to be embedded.
63 // configMap.put(FelixConstants.EMBEDDED_EXECUTION_PROP, "true");
64 // Add core OSGi packages to be exported from the class path
65 // via the system bundle.
66 configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES, "org.osgi.framework; version=1.3.0," + "org.osgi.service.packageadmin; version=1.2.0,"
67 + "org.osgi.service.startlevel; version=1.0.0," + "org.osgi.service.url; version=1.0.0");
68
69 configMap.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
70
71 // Explicitly specify the directory to use for caching bundles.
72 // configMap.put(BundleCache.CACHE_PROFILE_DIR_PROP, "cache");
73
74 try {
75 // Create host activator;
76
77 List<Object> list = new ArrayList<Object>();
78
79 // list.add(new HostActivator());
80 configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.xml.sax, org.xml.sax.helpers, javax.xml.parsers, javax.naming");
81 configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
82 configMap.put("felix.log.level", "4");
83
84 // Now create an instance of the framework with
85 // our configuration properties and activator.
86 felix = new Felix(configMap);
87 felix.init();
88
89 // otherProps.put(Constants.FRAMEWORK_STORAGE, "bundles");
90
91 otherProps.put(AutoProcessor.AUTO_DEPLOY_DIR_PROPERTY, AutoProcessor.AUTO_DEPLOY_DIR_VALUE);
92 otherProps.put(AutoProcessor.AUTO_DEPLOY_ACTION_PROPERTY, AutoProcessor.AUTO_DEPLOY_START_VALUE + "," + AutoProcessor.AUTO_DEPLOY_INSTALL_VALUE);
93
94 BundleContext felixBudleContext = felix.getBundleContext();
95
96 AutoProcessor.process(otherProps, felixBudleContext);
97 // listen to errors
98 felixBudleContext.addFrameworkListener(frameworkErrorListener);
99 felixBudleContext.addBundleListener(myBundleListener);
100 // Now start Felix instance.
101 felix.start();
102 System.out.println("felix started");
103
104 } catch (Exception ex) {
105 ex.printStackTrace();
106 }
107 }
108
109 public void stop() throws BundleException {
110 felix.stop();
111 }
112
113 public Bundle[] getInstalledBundles() {
114 // Use the system bundle activator to gain external
115 // access to the set of installed bundles.
116 return null;// m_activator.getBundles();
117 }
118118 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.osgi.framework.FrameworkEvent;
30 import org.osgi.framework.FrameworkListener;
31
32 public class FrameworkErrorListener implements FrameworkListener {
33
34 public List<FrameworkEvent> errorList = new ArrayList<FrameworkEvent>();
35
36 public void frameworkEvent(FrameworkEvent fe) {
37 if (fe.getType() == FrameworkEvent.ERROR) {
38 errorList.add(fe);
39
40 }
41 }
42
43 private void dump(FrameworkEvent fe) {
44 Throwable t = fe.getThrowable();
45 String tString = null;
46 if (t != null) {
47 tString = t.toString();
48 }
49 System.out.println("Framework ERROR:" + ", source " + fe.getSource() + ", bundle=" + fe.getBundle() + ", ex=" + tString);
50 if (t != null) {
51 t.printStackTrace();
52 }
53 }
54
55 public void dumpAll() {
56 for (int i = 0; i < errorList.size(); i++) {
57 FrameworkEvent fe = (FrameworkEvent) errorList.get(i);
58 dump(fe);
59 }
60 }
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.osgi.framework.FrameworkEvent;
30 import org.osgi.framework.FrameworkListener;
31
32 public class FrameworkErrorListener implements FrameworkListener {
33
34 public List<FrameworkEvent> errorList = new ArrayList<FrameworkEvent>();
35
36 public void frameworkEvent(FrameworkEvent fe) {
37 if (fe.getType() == FrameworkEvent.ERROR) {
38 errorList.add(fe);
39
40 }
41 }
42
43 private void dump(FrameworkEvent fe) {
44 Throwable t = fe.getThrowable();
45 String tString = null;
46 if (t != null) {
47 tString = t.toString();
48 }
49 System.out.println("Framework ERROR:" + ", source " + fe.getSource() + ", bundle=" + fe.getBundle() + ", ex=" + tString);
50 if (t != null) {
51 t.printStackTrace();
52 }
53 }
54
55 public void dumpAll() {
56 for (int i = 0; i < errorList.size(); i++) {
57 FrameworkEvent fe = (FrameworkEvent) errorList.get(i);
58 dump(fe);
59 }
60 }
61 }
0 Apache License
1 Version 2.0, January 2004
2 http://www.apache.org/licenses/
3
4 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
5
6 1. Definitions.
7
8 "License" shall mean the terms and conditions for use, reproduction,
9 and distribution as defined by Sections 1 through 9 of this document.
10
11 "Licensor" shall mean the copyright owner or entity authorized by
12 the copyright owner that is granting the License.
13
14 "Legal Entity" shall mean the union of the acting entity and all
15 other entities that control, are controlled by, or are under common
16 control with that entity. For the purposes of this definition,
17 "control" means (i) the power, direct or indirect, to cause the
18 direction or management of such entity, whether by contract or
19 otherwise, or (ii) ownership of fifty percent (50%) or more of the
20 outstanding shares, or (iii) beneficial ownership of such entity.
21
22 "You" (or "Your") shall mean an individual or Legal Entity
23 exercising permissions granted by this License.
24
25 "Source" form shall mean the preferred form for making modifications,
26 including but not limited to software source code, documentation
27 source, and configuration files.
28
29 "Object" form shall mean any form resulting from mechanical
30 transformation or translation of a Source form, including but
31 not limited to compiled object code, generated documentation,
32 and conversions to other media types.
33
34 "Work" shall mean the work of authorship, whether in Source or
35 Object form, made available under the License, as indicated by a
36 copyright notice that is included in or attached to the work
37 (an example is provided in the Appendix below).
38
39 "Derivative Works" shall mean any work, whether in Source or Object
40 form, that is based on (or derived from) the Work and for which the
41 editorial revisions, annotations, elaborations, or other modifications
42 represent, as a whole, an original work of authorship. For the purposes
43 of this License, Derivative Works shall not include works that remain
44 separable from, or merely link (or bind by name) to the interfaces of,
45 the Work and Derivative Works thereof.
46
47 "Contribution" shall mean any work of authorship, including
48 the original version of the Work and any modifications or additions
49 to that Work or Derivative Works thereof, that is intentionally
50 submitted to Licensor for inclusion in the Work by the copyright owner
51 or by an individual or Legal Entity authorized to submit on behalf of
52 the copyright owner. For the purposes of this definition, "submitted"
53 means any form of electronic, verbal, or written communication sent
54 to the Licensor or its representatives, including but not limited to
55 communication on electronic mailing lists, source code control systems,
56 and issue tracking systems that are managed by, or on behalf of, the
57 Licensor for the purpose of discussing and improving the Work, but
58 excluding communication that is conspicuously marked or otherwise
59 designated in writing by the copyright owner as "Not a Contribution."
60
61 "Contributor" shall mean Licensor and any individual or Legal Entity
62 on behalf of whom a Contribution has been received by Licensor and
63 subsequently incorporated within the Work.
64
65 2. Grant of Copyright License. Subject to the terms and conditions of
66 this License, each Contributor hereby grants to You a perpetual,
67 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68 copyright license to reproduce, prepare Derivative Works of,
69 publicly display, publicly perform, sublicense, and distribute the
70 Work and such Derivative Works in Source or Object form.
71
72 3. Grant of Patent License. Subject to the terms and conditions of
73 this License, each Contributor hereby grants to You a perpetual,
74 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75 (except as stated in this section) patent license to make, have made,
76 use, offer to sell, sell, import, and otherwise transfer the Work,
77 where such license applies only to those patent claims licensable
78 by such Contributor that are necessarily infringed by their
79 Contribution(s) alone or by combination of their Contribution(s)
80 with the Work to which such Contribution(s) was submitted. If You
81 institute patent litigation against any entity (including a
82 cross-claim or counterclaim in a lawsuit) alleging that the Work
83 or a Contribution incorporated within the Work constitutes direct
84 or contributory patent infringement, then any patent licenses
85 granted to You under this License for that Work shall terminate
86 as of the date such litigation is filed.
87
88 4. Redistribution. You may reproduce and distribute copies of the
89 Work or Derivative Works thereof in any medium, with or without
90 modifications, and in Source or Object form, provided that You
91 meet the following conditions:
92
93 (a) You must give any other recipients of the Work or
94 Derivative Works a copy of this License; and
95
96 (b) You must cause any modified files to carry prominent notices
97 stating that You changed the files; and
98
99 (c) You must retain, in the Source form of any Derivative Works
100 that You distribute, all copyright, patent, trademark, and
101 attribution notices from the Source form of the Work,
102 excluding those notices that do not pertain to any part of
103 the Derivative Works; and
104
105 (d) If the Work includes a "NOTICE" text file as part of its
106 distribution, then any Derivative Works that You distribute must
107 include a readable copy of the attribution notices contained
108 within such NOTICE file, excluding those notices that do not
109 pertain to any part of the Derivative Works, in at least one
110 of the following places: within a NOTICE text file distributed
111 as part of the Derivative Works; within the Source form or
112 documentation, if provided along with the Derivative Works; or,
113 within a display generated by the Derivative Works, if and
114 wherever such third-party notices normally appear. The contents
115 of the NOTICE file are for informational purposes only and
116 do not modify the License. You may add Your own attribution
117 notices within Derivative Works that You distribute, alongside
118 or as an addendum to the NOTICE text from the Work, provided
119 that such additional attribution notices cannot be construed
120 as modifying the License.
121
122 You may add Your own copyright statement to Your modifications and
123 may provide additional or different license terms and conditions
124 for use, reproduction, or distribution of Your modifications, or
125 for any such Derivative Works as a whole, provided Your use,
126 reproduction, and distribution of the Work otherwise complies with
127 the conditions stated in this License.
128
129 5. Submission of Contributions. Unless You explicitly state otherwise,
130 any Contribution intentionally submitted for inclusion in the Work
131 by You to the Licensor shall be under the terms and conditions of
132 this License, without any additional terms or conditions.
133 Notwithstanding the above, nothing herein shall supersede or modify
134 the terms of any separate license agreement you may have executed
135 with Licensor regarding such Contributions.
136
137 6. Trademarks. This License does not grant permission to use the trade
138 names, trademarks, service marks, or product names of the Licensor,
139 except as required for reasonable and customary use in describing the
140 origin of the Work and reproducing the content of the NOTICE file.
141
142 7. Disclaimer of Warranty. Unless required by applicable law or
143 agreed to in writing, Licensor provides the Work (and each
144 Contributor provides its Contributions) on an "AS IS" BASIS,
145 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146 implied, including, without limitation, any warranties or conditions
147 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148 PARTICULAR PURPOSE. You are solely responsible for determining the
149 appropriateness of using or redistributing the Work and assume any
150 risks associated with Your exercise of permissions under this License.
151
152 8. Limitation of Liability. In no event and under no legal theory,
153 whether in tort (including negligence), contract, or otherwise,
154 unless required by applicable law (such as deliberate and grossly
155 negligent acts) or agreed to in writing, shall any Contributor be
156 liable to You for damages, including any direct, indirect, special,
157 incidental, or consequential damages of any character arising as a
158 result of this License or out of the use or inability to use the
159 Work (including but not limited to damages for loss of goodwill,
160 work stoppage, computer failure or malfunction, or any and all
161 other commercial damages or losses), even if such Contributor
162 has been advised of the possibility of such damages.
163
164 9. Accepting Warranty or Additional Liability. While redistributing
165 the Work or Derivative Works thereof, You may choose to offer,
166 and charge a fee for, acceptance of support, warranty, indemnity,
167 or other liability obligations and/or rights consistent with this
168 License. However, in accepting such obligations, You may act only
169 on Your own behalf and on Your sole responsibility, not on behalf
170 of any other Contributor, and only if You agree to indemnify,
171 defend, and hold each Contributor harmless for any liability
172 incurred by, or claims asserted against, such Contributor by reason
173 of your accepting any such warranty or additional liability.
174
175 END OF TERMS AND CONDITIONS
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <parent>
5 <groupId>org.slf4j</groupId>
6 <artifactId>slf4j-parent</artifactId>
7 <version>1.7.25</version>
8 </parent>
9
10 <modelVersion>4.0.0</modelVersion>
11
12 <artifactId>jcl-over-slf4j</artifactId>
13 <packaging>jar</packaging>
14 <name>JCL 1.2 implemented over SLF4J</name>
15 <description>JCL 1.2 implemented over SLF4J</description>
16 <url>http://www.slf4j.org</url>
17
18 <dependencies>
19 <dependency>
20 <groupId>org.slf4j</groupId>
21 <artifactId>slf4j-api</artifactId>
22 </dependency>
23 <dependency>
24 <groupId>org.slf4j</groupId>
25 <artifactId>slf4j-jdk14</artifactId>
26 <scope>test</scope>
27 </dependency>
28 </dependencies>
29
30 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <parent>
5 <groupId>org.slf4j</groupId>
6 <artifactId>slf4j-parent</artifactId>
7 <version>1.7.26</version>
8 </parent>
9
10 <modelVersion>4.0.0</modelVersion>
11
12 <artifactId>jcl-over-slf4j</artifactId>
13 <packaging>jar</packaging>
14 <name>JCL 1.2 implemented over SLF4J</name>
15 <description>JCL 1.2 implemented over SLF4J</description>
16 <url>http://www.slf4j.org</url>
17
18 <dependencies>
19 <dependency>
20 <groupId>org.slf4j</groupId>
21 <artifactId>slf4j-api</artifactId>
22 </dependency>
23 <dependency>
24 <groupId>org.slf4j</groupId>
25 <artifactId>slf4j-jdk14</artifactId>
26 <scope>test</scope>
27 </dependency>
28 </dependencies>
29
30
31 </project>
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging;
17
18 /**
19 * <p>A simple logging interface abstracting logging APIs. In order to be
20 * instantiated successfully by {@link LogFactory}, classes that implement
21 * this interface must have a constructor that takes a single String
22 * parameter representing the "name" of this Log.</p>
23 *
24 * <p> The six logging levels used by <code>Log</code> are (in order):
25 * <ol>
26 * <li>trace (the least serious)</li>
27 * <li>debug</li>
28 * <li>info</li>
29 * <li>warn</li>
30 * <li>error</li>
31 * <li>fatal (the most serious)</li>
32 * </ol>
33 * The mapping of these log levels to the concepts used by the underlying
34 * logging system is implementation dependent.
35 * The implementation should ensure, though, that this ordering behaves
36 * as expected.</p>
37 *
38 * <p>Performance is often a logging concern.
39 * By examining the appropriate property,
40 * a component can avoid expensive operations (producing information
41 * to be logged).</p>
42 *
43 * <p> For example,
44 * <code><pre>
45 * if (log.isDebugEnabled()) {
46 * ... do something expensive ...
47 * log.debug(theResult);
48 * }
49 * </pre></code>
50 * </p>
51 *
52 * <p>Configuration of the underlying logging system will generally be done
53 * external to the Logging APIs, through whatever mechanism is supported by
54 * that system.</p>
55 *
56 * <p style="color: #E40; font-weight: bold;">Please note that this interface is identical to that found in JCL 1.1.1.</p>
57 *
58 * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
59 * @author Rod Waldhoff
60 * @version $Id: Log.java,v 1.19 2004/06/06 21:16:04 rdonkin Exp $
61 */
62 public interface Log {
63
64 // ----------------------------------------------------- Logging Properties
65
66 /**
67 * <p> Is debug logging currently enabled? </p>
68 *
69 * <p> Call this method to prevent having to perform expensive operations
70 * (for example, <code>String</code> concatenation)
71 * when the log level is more than debug. </p>
72 */
73 public boolean isDebugEnabled();
74
75 /**
76 * <p> Is error logging currently enabled? </p>
77 *
78 * <p> Call this method to prevent having to perform expensive operations
79 * (for example, <code>String</code> concatenation)
80 * when the log level is more than error. </p>
81 */
82 public boolean isErrorEnabled();
83
84 /**
85 * <p> Is fatal logging currently enabled? </p>
86 *
87 * <p> Call this method to prevent having to perform expensive operations
88 * (for example, <code>String</code> concatenation)
89 * when the log level is more than fatal. </p>
90 */
91 public boolean isFatalEnabled();
92
93 /**
94 * <p> Is info logging currently enabled? </p>
95 *
96 * <p> Call this method to prevent having to perform expensive operations
97 * (for example, <code>String</code> concatenation)
98 * when the log level is more than info. </p>
99 *
100 * @return true if info enabled, false otherwise
101 */
102 public boolean isInfoEnabled();
103
104 /**
105 * <p> Is trace logging currently enabled? </p>
106 *
107 * <p> Call this method to prevent having to perform expensive operations
108 * (for example, <code>String</code> concatenation)
109 * when the log level is more than trace. </p>
110 *
111 * @return true if trace enabled, false otherwise
112 */
113 public boolean isTraceEnabled();
114
115 /**
116 * <p> Is warn logging currently enabled? </p>
117 *
118 * <p> Call this method to prevent having to perform expensive operations
119 * (for example, <code>String</code> concatenation)
120 * when the log level is more than warn. </p>
121 */
122 public boolean isWarnEnabled();
123
124 // -------------------------------------------------------- Logging Methods
125
126 /**
127 * <p> Log a message with trace log level. </p>
128 *
129 * @param message log this message
130 */
131 public void trace(Object message);
132
133 /**
134 * <p> Log an error with trace log level. </p>
135 *
136 * @param message log this message
137 * @param t log this cause
138 */
139 public void trace(Object message, Throwable t);
140
141 /**
142 * <p> Log a message with debug log level. </p>
143 *
144 * @param message log this message
145 */
146 public void debug(Object message);
147
148 /**
149 * <p> Log an error with debug log level. </p>
150 *
151 * @param message log this message
152 * @param t log this cause
153 */
154 public void debug(Object message, Throwable t);
155
156 /**
157 * <p> Log a message with info log level. </p>
158 *
159 * @param message log this message
160 */
161 public void info(Object message);
162
163 /**
164 * <p> Log an error with info log level. </p>
165 *
166 * @param message log this message
167 * @param t log this cause
168 */
169 public void info(Object message, Throwable t);
170
171 /**
172 * <p> Log a message with warn log level. </p>
173 *
174 * @param message log this message
175 */
176 public void warn(Object message);
177
178 /**
179 * <p> Log an error with warn log level. </p>
180 *
181 * @param message log this message
182 * @param t log this cause
183 */
184 public void warn(Object message, Throwable t);
185
186 /**
187 * <p> Log a message with error log level. </p>
188 *
189 * @param message log this message
190 */
191 public void error(Object message);
192
193 /**
194 * <p> Log an error with error log level. </p>
195 *
196 * @param message log this message
197 * @param t log this cause
198 */
199 public void error(Object message, Throwable t);
200
201 /**
202 * <p> Log a message with fatal log level. </p>
203 *
204 * @param message log this message
205 */
206 public void fatal(Object message);
207
208 /**
209 * <p> Log an error with fatal log level. </p>
210 *
211 * @param message log this message
212 * @param t log this cause
213 */
214 public void fatal(Object message, Throwable t);
215
216 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging;
17
18 /**
19 * <p>A simple logging interface abstracting logging APIs. In order to be
20 * instantiated successfully by {@link LogFactory}, classes that implement
21 * this interface must have a constructor that takes a single String
22 * parameter representing the "name" of this Log.</p>
23 *
24 * <p> The six logging levels used by <code>Log</code> are (in order):
25 * <ol>
26 * <li>trace (the least serious)</li>
27 * <li>debug</li>
28 * <li>info</li>
29 * <li>warn</li>
30 * <li>error</li>
31 * <li>fatal (the most serious)</li>
32 * </ol>
33 * The mapping of these log levels to the concepts used by the underlying
34 * logging system is implementation dependent.
35 * The implementation should ensure, though, that this ordering behaves
36 * as expected.</p>
37 *
38 * <p>Performance is often a logging concern.
39 * By examining the appropriate property,
40 * a component can avoid expensive operations (producing information
41 * to be logged).</p>
42 *
43 * <p> For example,
44 * <code><pre>
45 * if (log.isDebugEnabled()) {
46 * ... do something expensive ...
47 * log.debug(theResult);
48 * }
49 * </pre></code>
50 * </p>
51 *
52 * <p>Configuration of the underlying logging system will generally be done
53 * external to the Logging APIs, through whatever mechanism is supported by
54 * that system.</p>
55 *
56 * <p style="color: #E40; font-weight: bold;">Please note that this interface is identical to that found in JCL 1.1.1.</p>
57 *
58 * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
59 * @author Rod Waldhoff
60 * @version $Id: Log.java,v 1.19 2004/06/06 21:16:04 rdonkin Exp $
61 */
62 public interface Log {
63
64 // ----------------------------------------------------- Logging Properties
65
66 /**
67 * <p> Is debug logging currently enabled? </p>
68 *
69 * <p> Call this method to prevent having to perform expensive operations
70 * (for example, <code>String</code> concatenation)
71 * when the log level is more than debug. </p>
72 */
73 public boolean isDebugEnabled();
74
75 /**
76 * <p> Is error logging currently enabled? </p>
77 *
78 * <p> Call this method to prevent having to perform expensive operations
79 * (for example, <code>String</code> concatenation)
80 * when the log level is more than error. </p>
81 */
82 public boolean isErrorEnabled();
83
84 /**
85 * <p> Is fatal logging currently enabled? </p>
86 *
87 * <p> Call this method to prevent having to perform expensive operations
88 * (for example, <code>String</code> concatenation)
89 * when the log level is more than fatal. </p>
90 */
91 public boolean isFatalEnabled();
92
93 /**
94 * <p> Is info logging currently enabled? </p>
95 *
96 * <p> Call this method to prevent having to perform expensive operations
97 * (for example, <code>String</code> concatenation)
98 * when the log level is more than info. </p>
99 *
100 * @return true if info enabled, false otherwise
101 */
102 public boolean isInfoEnabled();
103
104 /**
105 * <p> Is trace logging currently enabled? </p>
106 *
107 * <p> Call this method to prevent having to perform expensive operations
108 * (for example, <code>String</code> concatenation)
109 * when the log level is more than trace. </p>
110 *
111 * @return true if trace enabled, false otherwise
112 */
113 public boolean isTraceEnabled();
114
115 /**
116 * <p> Is warn logging currently enabled? </p>
117 *
118 * <p> Call this method to prevent having to perform expensive operations
119 * (for example, <code>String</code> concatenation)
120 * when the log level is more than warn. </p>
121 */
122 public boolean isWarnEnabled();
123
124 // -------------------------------------------------------- Logging Methods
125
126 /**
127 * <p> Log a message with trace log level. </p>
128 *
129 * @param message log this message
130 */
131 public void trace(Object message);
132
133 /**
134 * <p> Log an error with trace log level. </p>
135 *
136 * @param message log this message
137 * @param t log this cause
138 */
139 public void trace(Object message, Throwable t);
140
141 /**
142 * <p> Log a message with debug log level. </p>
143 *
144 * @param message log this message
145 */
146 public void debug(Object message);
147
148 /**
149 * <p> Log an error with debug log level. </p>
150 *
151 * @param message log this message
152 * @param t log this cause
153 */
154 public void debug(Object message, Throwable t);
155
156 /**
157 * <p> Log a message with info log level. </p>
158 *
159 * @param message log this message
160 */
161 public void info(Object message);
162
163 /**
164 * <p> Log an error with info log level. </p>
165 *
166 * @param message log this message
167 * @param t log this cause
168 */
169 public void info(Object message, Throwable t);
170
171 /**
172 * <p> Log a message with warn log level. </p>
173 *
174 * @param message log this message
175 */
176 public void warn(Object message);
177
178 /**
179 * <p> Log an error with warn log level. </p>
180 *
181 * @param message log this message
182 * @param t log this cause
183 */
184 public void warn(Object message, Throwable t);
185
186 /**
187 * <p> Log a message with error log level. </p>
188 *
189 * @param message log this message
190 */
191 public void error(Object message);
192
193 /**
194 * <p> Log an error with error log level. </p>
195 *
196 * @param message log this message
197 * @param t log this cause
198 */
199 public void error(Object message, Throwable t);
200
201 /**
202 * <p> Log a message with fatal log level. </p>
203 *
204 * @param message log this message
205 */
206 public void fatal(Object message);
207
208 /**
209 * <p> Log an error with fatal log level. </p>
210 *
211 * @param message log this message
212 * @param t log this cause
213 */
214 public void fatal(Object message, Throwable t);
215
216 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging;
17
18 /**
19 * <p>
20 * An exception that is thrown only if a suitable <code>LogFactory</code> or
21 * <code>Log</code> instance cannot be created by the corresponding factory
22 * methods.
23 * </p>
24 *
25 * <p>
26 * In this version of JCL, this exception will never be thrown in practice.
27 * However, it is included here to ensure total compile time and run time
28 * compatibility with the original JCL 1.0.4.
29 *
30 * @author Craig R. McClanahan
31 */
32
33 public class LogConfigurationException extends RuntimeException {
34
35 private static final long serialVersionUID = 8486587136871052495L;
36
37 /**
38 * Construct a new exception with <code>null</code> as its detail message.
39 */
40 public LogConfigurationException() {
41 super();
42 }
43
44 /**
45 * Construct a new exception with the specified detail message.
46 *
47 * @param message
48 * The detail message
49 */
50 public LogConfigurationException(String message) {
51 super(message);
52 }
53
54 /**
55 * Construct a new exception with the specified cause and a derived detail
56 * message.
57 *
58 * @param cause
59 * The underlying cause
60 */
61 public LogConfigurationException(Throwable cause) {
62
63 this((cause == null) ? null : cause.toString(), cause);
64
65 }
66
67 /**
68 * Construct a new exception with the specified detail message and cause.
69 *
70 * @param message
71 * The detail message
72 * @param cause
73 * The underlying cause
74 */
75 public LogConfigurationException(String message, Throwable cause) {
76 super(message + " (Caused by " + cause + ")");
77 this.cause = cause; // Two-argument version requires JDK 1.4 or later
78 }
79
80 /**
81 * The underlying cause of this exception.
82 */
83 protected Throwable cause = null;
84
85 /**
86 * Return the underlying cause of this exception (if any).
87 */
88 public Throwable getCause() {
89 return (this.cause);
90 }
91
92 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging;
17
18 /**
19 * <p>
20 * An exception that is thrown only if a suitable <code>LogFactory</code> or
21 * <code>Log</code> instance cannot be created by the corresponding factory
22 * methods.
23 * </p>
24 *
25 * <p>
26 * In this version of JCL, this exception will never be thrown in practice.
27 * However, it is included here to ensure total compile time and run time
28 * compatibility with the original JCL 1.0.4.
29 *
30 * @author Craig R. McClanahan
31 */
32
33 public class LogConfigurationException extends RuntimeException {
34
35 private static final long serialVersionUID = 8486587136871052495L;
36
37 /**
38 * Construct a new exception with <code>null</code> as its detail message.
39 */
40 public LogConfigurationException() {
41 super();
42 }
43
44 /**
45 * Construct a new exception with the specified detail message.
46 *
47 * @param message
48 * The detail message
49 */
50 public LogConfigurationException(String message) {
51 super(message);
52 }
53
54 /**
55 * Construct a new exception with the specified cause and a derived detail
56 * message.
57 *
58 * @param cause
59 * The underlying cause
60 */
61 public LogConfigurationException(Throwable cause) {
62
63 this((cause == null) ? null : cause.toString(), cause);
64
65 }
66
67 /**
68 * Construct a new exception with the specified detail message and cause.
69 *
70 * @param message
71 * The detail message
72 * @param cause
73 * The underlying cause
74 */
75 public LogConfigurationException(String message, Throwable cause) {
76 super(message + " (Caused by " + cause + ")");
77 this.cause = cause; // Two-argument version requires JDK 1.4 or later
78 }
79
80 /**
81 * The underlying cause of this exception.
82 */
83 protected Throwable cause = null;
84
85 /**
86 * Return the underlying cause of this exception (if any).
87 */
88 public Throwable getCause() {
89 return (this.cause);
90 }
91
92 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging;
17
18 import java.util.Hashtable;
19
20 import org.apache.commons.logging.impl.SLF4JLogFactory;
21
22 /**
23 * <p>
24 * Factory for creating {@link Log} instances, which always delegates to an
25 * instance of {@link SLF4JLogFactory}.
26 *
27 * </p>
28 *
29 * @author Craig R. McClanahan
30 * @author Costin Manolache
31 * @author Richard A. Sitze
32 * @author Ceki G&uuml;lc&uuml;
33 */
34
35 @SuppressWarnings("rawtypes")
36 public abstract class LogFactory {
37
38 static String UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J = "http://www.slf4j.org/codes.html#unsupported_operation_in_jcl_over_slf4j";
39
40 static LogFactory logFactory = new SLF4JLogFactory();
41
42 /**
43 * The name (<code>priority</code>) of the key in the config file used to
44 * specify the priority of that particular config file. The associated value
45 * is a floating-point number; higher values take priority over lower values.
46 *
47 * <p>
48 * This property is not used but preserved here for compatibility.
49 */
50 public static final String PRIORITY_KEY = "priority";
51
52 /**
53 * The name (<code>use_tccl</code>) of the key in the config file used to
54 * specify whether logging classes should be loaded via the thread context
55 * class loader (TCCL), or not. By default, the TCCL is used.
56 *
57 * <p>
58 * This property is not used but preserved here for compatibility.
59 */
60 public static final String TCCL_KEY = "use_tccl";
61
62 /**
63 * The name of the property used to identify the LogFactory implementation
64 * class name.
65 * <p>
66 * This property is not used but preserved here for compatibility.
67 */
68 public static final String FACTORY_PROPERTY = "org.apache.commons.logging.LogFactory";
69
70 /**
71 * The fully qualified class name of the fallback <code>LogFactory</code>
72 * implementation class to use, if no other can be found.
73 *
74 * <p>
75 * This property is not used but preserved here for compatibility.
76 */
77 public static final String FACTORY_DEFAULT = "org.apache.commons.logging.impl.SLF4JLogFactory";
78
79 /**
80 * The name of the properties file to search for.
81 * <p>
82 * This property is not used but preserved here for compatibility.
83 */
84 public static final String FACTORY_PROPERTIES = "commons-logging.properties";
85
86 /**
87 * JDK1.3+ <a href="http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service%20Provider">
88 * 'Service Provider' specification</a>.
89 * <p>
90 * This property is not used but preserved here for compatibility.
91 */
92 protected static final String SERVICE_ID = "META-INF/services/org.apache.commons.logging.LogFactory";
93
94 /**
95 * The name (<code>org.apache.commons.logging.diagnostics.dest</code>) of
96 * the property used to enable internal commons-logging diagnostic output, in
97 * order to get information on what logging implementations are being
98 * discovered, what classloaders they are loaded through, etc.
99 *
100 * <p>
101 * This property is not used but preserved here for compatibility.
102 */
103 public static final String DIAGNOSTICS_DEST_PROPERTY = "org.apache.commons.logging.diagnostics.dest";
104
105 /**
106 * <p>
107 * Setting this system property value allows the <code>Hashtable</code> used
108 * to store classloaders to be substituted by an alternative implementation.
109 * <p>
110 * This property is not used but preserved here for compatibility.
111 */
112 public static final String HASHTABLE_IMPLEMENTATION_PROPERTY = "org.apache.commons.logging.LogFactory.HashtableImpl";
113
114 /**
115 * The previously constructed <code>LogFactory</code> instances, keyed by
116 * the <code>ClassLoader</code> with which it was created.
117 *
118 * <p>
119 * This property is not used but preserved here for compatibility.
120 */
121 protected static Hashtable factories = null;
122
123 /**
124 * <p>
125 * This property is not used but preserved here for compatibility.
126 */
127 protected static LogFactory nullClassLoaderFactory = null;
128
129 /**
130 * Protected constructor that is not available for public use.
131 */
132 protected LogFactory() {
133 }
134
135 // --------------------------------------------------------- Public Methods
136
137 /**
138 * Return the configuration attribute with the specified name (if any), or
139 * <code>null</code> if there is no such attribute.
140 *
141 * @param name Name of the attribute to return
142 * @return configuration attribute
143 */
144 public abstract Object getAttribute(String name);
145
146 /**
147 * Return an array containing the names of all currently defined configuration
148 * attributes. If there are no such attributes, a zero length array is
149 * returned.
150 *
151 * @return names of all currently defined configuration attributes
152 */
153 public abstract String[] getAttributeNames();
154
155 /**
156 * Convenience method to derive a name from the specified class and call
157 * <code>getInstance(String)</code> with it.
158 *
159 * @param clazz
160 * Class for which a suitable Log name will be derived
161 *
162 * @exception LogConfigurationException
163 * if a suitable <code>Log</code> instance cannot be
164 * returned
165 */
166 public abstract Log getInstance(Class clazz) throws LogConfigurationException;
167
168 /**
169 * <p>
170 * Construct (if necessary) and return a <code>Log</code> instance, using
171 * the factory's current set of configuration attributes.
172 * </p>
173 *
174 * <p>
175 * <strong>NOTE </strong>- Depending upon the implementation of the
176 * <code>LogFactory</code> you are using, the <code>Log</code> instance
177 * you are returned may or may not be local to the current application, and
178 * may or may not be returned again on a subsequent call with the same name
179 * argument.
180 * </p>
181 *
182 * @param name
183 * Logical name of the <code>Log</code> instance to be
184 * returned (the meaning of this name is only known to the
185 * underlying logging implementation that is being wrapped)
186 *
187 * @exception LogConfigurationException
188 * if a suitable <code>Log</code> instance cannot be
189 * returned
190 */
191 public abstract Log getInstance(String name) throws LogConfigurationException;
192
193 /**
194 * Release any internal references to previously created {@link Log}instances
195 * returned by this factory. This is useful in environments like servlet
196 * containers, which implement application reloading by throwing away a
197 * ClassLoader. Dangling references to objects in that class loader would
198 * prevent garbage collection.
199 */
200 public abstract void release();
201
202 /**
203 * Remove any configuration attribute associated with the specified name. If
204 * there is no such attribute, no action is taken.
205 *
206 * @param name
207 * Name of the attribute to remove
208 */
209 public abstract void removeAttribute(String name);
210
211 /**
212 * Set the configuration attribute with the specified name. Calling this with
213 * a <code>null</code> value is equivalent to calling
214 * <code>removeAttribute(name)</code>.
215 *
216 * @param name
217 * Name of the attribute to set
218 * @param value
219 * Value of the attribute to set, or <code>null</code> to
220 * remove any setting for this attribute
221 */
222 public abstract void setAttribute(String name, Object value);
223
224 // --------------------------------------------------------- Static Methods
225
226 /**
227 * <p>
228 * Construct (if necessary) and return a <code>LogFactory</code> instance,
229 * using the following ordered lookup procedure to determine the name of the
230 * implementation class to be loaded.
231 * </p>
232 * <ul>
233 * <li>The <code>org.apache.commons.logging.LogFactory</code> system
234 * property.</li>
235 * <li>The JDK 1.3 Service Discovery mechanism</li>
236 * <li>Use the properties file <code>commons-logging.properties</code>
237 * file, if found in the class path of this class. The configuration file is
238 * in standard <code>java.util.Properties</code> format and contains the
239 * fully qualified name of the implementation class with the key being the
240 * system property defined above.</li>
241 * <li>Fall back to a default implementation class (
242 * <code>org.apache.commons.logging.impl.SLF4FLogFactory</code>).</li>
243 * </ul>
244 *
245 * <p>
246 * <em>NOTE</em>- If the properties file method of identifying the
247 * <code>LogFactory</code> implementation class is utilized, all of the
248 * properties defined in this file will be set as configuration attributes on
249 * the corresponding <code>LogFactory</code> instance.
250 * </p>
251 *
252 * @exception LogConfigurationException
253 * if the implementation class is not available or cannot
254 * be instantiated.
255 */
256 public static LogFactory getFactory() throws LogConfigurationException {
257 return logFactory;
258 }
259
260 /**
261 * Convenience method to return a named logger, without the application having
262 * to care about factories.
263 *
264 * @param clazz
265 * Class from which a log name will be derived
266 *
267 * @exception LogConfigurationException
268 * if a suitable <code>Log</code> instance cannot be
269 * returned
270 */
271 public static Log getLog(Class clazz) throws LogConfigurationException {
272 return (getFactory().getInstance(clazz));
273 }
274
275 /**
276 * Convenience method to return a named logger, without the application having
277 * to care about factories.
278 *
279 * @param name
280 * Logical name of the <code>Log</code> instance to be
281 * returned (the meaning of this name is only known to the
282 * underlying logging implementation that is being wrapped)
283 *
284 * @exception LogConfigurationException
285 * if a suitable <code>Log</code> instance cannot be
286 * returned
287 */
288 public static Log getLog(String name) throws LogConfigurationException {
289 return (getFactory().getInstance(name));
290 }
291
292 /**
293 * Release any internal references to previously created {@link LogFactory}
294 * instances that have been associated with the specified class loader (if
295 * any), after calling the instance method <code>release()</code> on each of
296 * them.
297 *
298 * @param classLoader
299 * ClassLoader for which to release the LogFactory
300 */
301 public static void release(ClassLoader classLoader) {
302 // since SLF4J based JCL does not make use of classloaders, there is nothing
303 // to do here
304 }
305
306 /**
307 * Release any internal references to previously created {@link LogFactory}
308 * instances, after calling the instance method <code>release()</code> on
309 * each of them. This is useful in environments like servlet containers, which
310 * implement application reloading by throwing away a ClassLoader. Dangling
311 * references to objects in that class loader would prevent garbage
312 * collection.
313 */
314 public static void releaseAll() {
315 // since SLF4J based JCL does not make use of classloaders, there is nothing
316 // to do here
317 }
318
319 /**
320 * Returns a string that uniquely identifies the specified object, including
321 * its class.
322 * <p>
323 * The returned string is of form "classname@hashcode", i.e. is the same as the
324 * return value of the Object.toString() method, but works even when the
325 * specified object's class has overridden the toString method.
326 *
327 * @param o
328 * may be null.
329 * @return a string of form classname@hashcode, or "null" if param o is null.
330 * @since 1.1
331 */
332 public static String objectId(Object o) {
333 if (o == null) {
334 return "null";
335 } else {
336 return o.getClass().getName() + "@" + System.identityHashCode(o);
337 }
338 }
339
340 // protected methods which were added in JCL 1.1. These are not used
341 // by SLF4JLogFactory
342
343 /**
344 * This method exists to ensure signature compatibility.
345 */
346 protected static Object createFactory(String factoryClass, ClassLoader classLoader) {
347 throw new UnsupportedOperationException("Operation [factoryClass] is not supported in jcl-over-slf4j. See also "
348 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
349 }
350
351 /**
352 * This method exists to ensure signature compatibility.
353 */
354 protected static ClassLoader directGetContextClassLoader() {
355 throw new UnsupportedOperationException("Operation [directGetContextClassLoader] is not supported in jcl-over-slf4j. See also "
356 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
357 }
358
359 /**
360 * This method exists to ensure signature compatibility.
361 */
362 protected static ClassLoader getContextClassLoader() throws LogConfigurationException {
363 throw new UnsupportedOperationException("Operation [getContextClassLoader] is not supported in jcl-over-slf4j. See also "
364 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
365 }
366
367 /**
368 * This method exists to ensure signature compatibility.
369 */
370 protected static ClassLoader getClassLoader(Class clazz) {
371 throw new UnsupportedOperationException("Operation [getClassLoader] is not supported in jcl-over-slf4j. See also "
372 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
373 }
374
375 /**
376 * This method exists to ensure signature compatibility.
377 */
378 protected static boolean isDiagnosticsEnabled() {
379 throw new UnsupportedOperationException("Operation [isDiagnosticsEnabled] is not supported in jcl-over-slf4j. See also "
380 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
381 }
382
383 /**
384 * This method exists to ensure signature compatibility.
385 */
386 protected static void logRawDiagnostic(String msg) {
387 throw new UnsupportedOperationException("Operation [logRawDiagnostic] is not supported in jcl-over-slf4j. See also "
388 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
389 }
390
391 /**
392 * This method exists to ensure signature compatibility.
393 */
394 protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader, final ClassLoader contextClassLoader) {
395 throw new UnsupportedOperationException("Operation [logRawDiagnostic] is not supported in jcl-over-slf4j. See also "
396 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
397 }
398
399 /**
400 * This method exists to ensure signature compatibility.
401 */
402 protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader) {
403 throw new UnsupportedOperationException("Operation [newFactory] is not supported in jcl-over-slf4j. See also "
404 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
405 }
406
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging;
17
18 import java.util.Hashtable;
19
20 import org.apache.commons.logging.impl.SLF4JLogFactory;
21
22 /**
23 * <p>
24 * Factory for creating {@link Log} instances, which always delegates to an
25 * instance of {@link SLF4JLogFactory}.
26 *
27 * </p>
28 *
29 * @author Craig R. McClanahan
30 * @author Costin Manolache
31 * @author Richard A. Sitze
32 * @author Ceki G&uuml;lc&uuml;
33 */
34
35 @SuppressWarnings("rawtypes")
36 public abstract class LogFactory {
37
38 static String UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J = "http://www.slf4j.org/codes.html#unsupported_operation_in_jcl_over_slf4j";
39
40 static LogFactory logFactory = new SLF4JLogFactory();
41
42 /**
43 * The name (<code>priority</code>) of the key in the config file used to
44 * specify the priority of that particular config file. The associated value
45 * is a floating-point number; higher values take priority over lower values.
46 *
47 * <p>
48 * This property is not used but preserved here for compatibility.
49 */
50 public static final String PRIORITY_KEY = "priority";
51
52 /**
53 * The name (<code>use_tccl</code>) of the key in the config file used to
54 * specify whether logging classes should be loaded via the thread context
55 * class loader (TCCL), or not. By default, the TCCL is used.
56 *
57 * <p>
58 * This property is not used but preserved here for compatibility.
59 */
60 public static final String TCCL_KEY = "use_tccl";
61
62 /**
63 * The name of the property used to identify the LogFactory implementation
64 * class name.
65 * <p>
66 * This property is not used but preserved here for compatibility.
67 */
68 public static final String FACTORY_PROPERTY = "org.apache.commons.logging.LogFactory";
69
70 /**
71 * The fully qualified class name of the fallback <code>LogFactory</code>
72 * implementation class to use, if no other can be found.
73 *
74 * <p>
75 * This property is not used but preserved here for compatibility.
76 */
77 public static final String FACTORY_DEFAULT = "org.apache.commons.logging.impl.SLF4JLogFactory";
78
79 /**
80 * The name of the properties file to search for.
81 * <p>
82 * This property is not used but preserved here for compatibility.
83 */
84 public static final String FACTORY_PROPERTIES = "commons-logging.properties";
85
86 /**
87 * JDK1.3+ <a href="http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service%20Provider">
88 * 'Service Provider' specification</a>.
89 * <p>
90 * This property is not used but preserved here for compatibility.
91 */
92 protected static final String SERVICE_ID = "META-INF/services/org.apache.commons.logging.LogFactory";
93
94 /**
95 * The name (<code>org.apache.commons.logging.diagnostics.dest</code>) of
96 * the property used to enable internal commons-logging diagnostic output, in
97 * order to get information on what logging implementations are being
98 * discovered, what classloaders they are loaded through, etc.
99 *
100 * <p>
101 * This property is not used but preserved here for compatibility.
102 */
103 public static final String DIAGNOSTICS_DEST_PROPERTY = "org.apache.commons.logging.diagnostics.dest";
104
105 /**
106 * <p>
107 * Setting this system property value allows the <code>Hashtable</code> used
108 * to store classloaders to be substituted by an alternative implementation.
109 * <p>
110 * This property is not used but preserved here for compatibility.
111 */
112 public static final String HASHTABLE_IMPLEMENTATION_PROPERTY = "org.apache.commons.logging.LogFactory.HashtableImpl";
113
114 /**
115 * The previously constructed <code>LogFactory</code> instances, keyed by
116 * the <code>ClassLoader</code> with which it was created.
117 *
118 * <p>
119 * This property is not used but preserved here for compatibility.
120 */
121 protected static Hashtable factories = null;
122
123 /**
124 * <p>
125 * This property is not used but preserved here for compatibility.
126 */
127 protected static LogFactory nullClassLoaderFactory = null;
128
129 /**
130 * Protected constructor that is not available for public use.
131 */
132 protected LogFactory() {
133 }
134
135 // --------------------------------------------------------- Public Methods
136
137 /**
138 * Return the configuration attribute with the specified name (if any), or
139 * <code>null</code> if there is no such attribute.
140 *
141 * @param name Name of the attribute to return
142 * @return configuration attribute
143 */
144 public abstract Object getAttribute(String name);
145
146 /**
147 * Return an array containing the names of all currently defined configuration
148 * attributes. If there are no such attributes, a zero length array is
149 * returned.
150 *
151 * @return names of all currently defined configuration attributes
152 */
153 public abstract String[] getAttributeNames();
154
155 /**
156 * Convenience method to derive a name from the specified class and call
157 * <code>getInstance(String)</code> with it.
158 *
159 * @param clazz
160 * Class for which a suitable Log name will be derived
161 *
162 * @exception LogConfigurationException
163 * if a suitable <code>Log</code> instance cannot be
164 * returned
165 */
166 public abstract Log getInstance(Class clazz) throws LogConfigurationException;
167
168 /**
169 * <p>
170 * Construct (if necessary) and return a <code>Log</code> instance, using
171 * the factory's current set of configuration attributes.
172 * </p>
173 *
174 * <p>
175 * <strong>NOTE </strong>- Depending upon the implementation of the
176 * <code>LogFactory</code> you are using, the <code>Log</code> instance
177 * you are returned may or may not be local to the current application, and
178 * may or may not be returned again on a subsequent call with the same name
179 * argument.
180 * </p>
181 *
182 * @param name
183 * Logical name of the <code>Log</code> instance to be
184 * returned (the meaning of this name is only known to the
185 * underlying logging implementation that is being wrapped)
186 *
187 * @exception LogConfigurationException
188 * if a suitable <code>Log</code> instance cannot be
189 * returned
190 */
191 public abstract Log getInstance(String name) throws LogConfigurationException;
192
193 /**
194 * Release any internal references to previously created {@link Log}instances
195 * returned by this factory. This is useful in environments like servlet
196 * containers, which implement application reloading by throwing away a
197 * ClassLoader. Dangling references to objects in that class loader would
198 * prevent garbage collection.
199 */
200 public abstract void release();
201
202 /**
203 * Remove any configuration attribute associated with the specified name. If
204 * there is no such attribute, no action is taken.
205 *
206 * @param name
207 * Name of the attribute to remove
208 */
209 public abstract void removeAttribute(String name);
210
211 /**
212 * Set the configuration attribute with the specified name. Calling this with
213 * a <code>null</code> value is equivalent to calling
214 * <code>removeAttribute(name)</code>.
215 *
216 * @param name
217 * Name of the attribute to set
218 * @param value
219 * Value of the attribute to set, or <code>null</code> to
220 * remove any setting for this attribute
221 */
222 public abstract void setAttribute(String name, Object value);
223
224 // --------------------------------------------------------- Static Methods
225
226 /**
227 * <p>
228 * Construct (if necessary) and return a <code>LogFactory</code> instance,
229 * using the following ordered lookup procedure to determine the name of the
230 * implementation class to be loaded.
231 * </p>
232 * <ul>
233 * <li>The <code>org.apache.commons.logging.LogFactory</code> system
234 * property.</li>
235 * <li>The JDK 1.3 Service Discovery mechanism</li>
236 * <li>Use the properties file <code>commons-logging.properties</code>
237 * file, if found in the class path of this class. The configuration file is
238 * in standard <code>java.util.Properties</code> format and contains the
239 * fully qualified name of the implementation class with the key being the
240 * system property defined above.</li>
241 * <li>Fall back to a default implementation class (
242 * <code>org.apache.commons.logging.impl.SLF4FLogFactory</code>).</li>
243 * </ul>
244 *
245 * <p>
246 * <em>NOTE</em>- If the properties file method of identifying the
247 * <code>LogFactory</code> implementation class is utilized, all of the
248 * properties defined in this file will be set as configuration attributes on
249 * the corresponding <code>LogFactory</code> instance.
250 * </p>
251 *
252 * @exception LogConfigurationException
253 * if the implementation class is not available or cannot
254 * be instantiated.
255 */
256 public static LogFactory getFactory() throws LogConfigurationException {
257 return logFactory;
258 }
259
260 /**
261 * Convenience method to return a named logger, without the application having
262 * to care about factories.
263 *
264 * @param clazz
265 * Class from which a log name will be derived
266 *
267 * @exception LogConfigurationException
268 * if a suitable <code>Log</code> instance cannot be
269 * returned
270 */
271 public static Log getLog(Class clazz) throws LogConfigurationException {
272 return (getFactory().getInstance(clazz));
273 }
274
275 /**
276 * Convenience method to return a named logger, without the application having
277 * to care about factories.
278 *
279 * @param name
280 * Logical name of the <code>Log</code> instance to be
281 * returned (the meaning of this name is only known to the
282 * underlying logging implementation that is being wrapped)
283 *
284 * @exception LogConfigurationException
285 * if a suitable <code>Log</code> instance cannot be
286 * returned
287 */
288 public static Log getLog(String name) throws LogConfigurationException {
289 return (getFactory().getInstance(name));
290 }
291
292 /**
293 * Release any internal references to previously created {@link LogFactory}
294 * instances that have been associated with the specified class loader (if
295 * any), after calling the instance method <code>release()</code> on each of
296 * them.
297 *
298 * @param classLoader
299 * ClassLoader for which to release the LogFactory
300 */
301 public static void release(ClassLoader classLoader) {
302 // since SLF4J based JCL does not make use of classloaders, there is nothing
303 // to do here
304 }
305
306 /**
307 * Release any internal references to previously created {@link LogFactory}
308 * instances, after calling the instance method <code>release()</code> on
309 * each of them. This is useful in environments like servlet containers, which
310 * implement application reloading by throwing away a ClassLoader. Dangling
311 * references to objects in that class loader would prevent garbage
312 * collection.
313 */
314 public static void releaseAll() {
315 // since SLF4J based JCL does not make use of classloaders, there is nothing
316 // to do here
317 }
318
319 /**
320 * Returns a string that uniquely identifies the specified object, including
321 * its class.
322 * <p>
323 * The returned string is of form "classname@hashcode", i.e. is the same as the
324 * return value of the Object.toString() method, but works even when the
325 * specified object's class has overridden the toString method.
326 *
327 * @param o
328 * may be null.
329 * @return a string of form classname@hashcode, or "null" if param o is null.
330 * @since 1.1
331 */
332 public static String objectId(Object o) {
333 if (o == null) {
334 return "null";
335 } else {
336 return o.getClass().getName() + "@" + System.identityHashCode(o);
337 }
338 }
339
340 // protected methods which were added in JCL 1.1. These are not used
341 // by SLF4JLogFactory
342
343 /**
344 * This method exists to ensure signature compatibility.
345 */
346 protected static Object createFactory(String factoryClass, ClassLoader classLoader) {
347 throw new UnsupportedOperationException("Operation [factoryClass] is not supported in jcl-over-slf4j. See also "
348 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
349 }
350
351 /**
352 * This method exists to ensure signature compatibility.
353 */
354 protected static ClassLoader directGetContextClassLoader() {
355 throw new UnsupportedOperationException("Operation [directGetContextClassLoader] is not supported in jcl-over-slf4j. See also "
356 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
357 }
358
359 /**
360 * This method exists to ensure signature compatibility.
361 */
362 protected static ClassLoader getContextClassLoader() throws LogConfigurationException {
363 throw new UnsupportedOperationException("Operation [getContextClassLoader] is not supported in jcl-over-slf4j. See also "
364 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
365 }
366
367 /**
368 * This method exists to ensure signature compatibility.
369 */
370 protected static ClassLoader getClassLoader(Class clazz) {
371 throw new UnsupportedOperationException("Operation [getClassLoader] is not supported in jcl-over-slf4j. See also "
372 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
373 }
374
375 /**
376 * This method exists to ensure signature compatibility.
377 */
378 protected static boolean isDiagnosticsEnabled() {
379 throw new UnsupportedOperationException("Operation [isDiagnosticsEnabled] is not supported in jcl-over-slf4j. See also "
380 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
381 }
382
383 /**
384 * This method exists to ensure signature compatibility.
385 */
386 protected static void logRawDiagnostic(String msg) {
387 throw new UnsupportedOperationException("Operation [logRawDiagnostic] is not supported in jcl-over-slf4j. See also "
388 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
389 }
390
391 /**
392 * This method exists to ensure signature compatibility.
393 */
394 protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader, final ClassLoader contextClassLoader) {
395 throw new UnsupportedOperationException("Operation [logRawDiagnostic] is not supported in jcl-over-slf4j. See also "
396 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
397 }
398
399 /**
400 * This method exists to ensure signature compatibility.
401 */
402 protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader) {
403 throw new UnsupportedOperationException("Operation [newFactory] is not supported in jcl-over-slf4j. See also "
404 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
405 }
406
407407 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.Serializable;
19 import org.apache.commons.logging.Log;
20
21 /**
22 * <p>
23 * Trivial implementation of Log that throws away all messages. No configurable
24 * system properties are supported.
25 * </p>
26 *
27 * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
28 * @author Rod Waldhoff
29 * @version $Id: NoOpLog.java,v 1.8 2004/06/06 21:13:12 rdonkin Exp $
30 */
31 public class NoOpLog implements Log, Serializable {
32 private static final long serialVersionUID = 561423906191706148L;
33
34 /** Convenience constructor */
35 public NoOpLog() {
36 }
37
38 /** Base constructor */
39 public NoOpLog(String name) {
40 }
41
42 /** Do nothing */
43 public void trace(Object message) {
44 }
45
46 /** Do nothing */
47 public void trace(Object message, Throwable t) {
48 }
49
50 /** Do nothing */
51 public void debug(Object message) {
52 }
53
54 /** Do nothing */
55 public void debug(Object message, Throwable t) {
56 }
57
58 /** Do nothing */
59 public void info(Object message) {
60 }
61
62 /** Do nothing */
63 public void info(Object message, Throwable t) {
64 }
65
66 /** Do nothing */
67 public void warn(Object message) {
68 }
69
70 /** Do nothing */
71 public void warn(Object message, Throwable t) {
72 }
73
74 /** Do nothing */
75 public void error(Object message) {
76 }
77
78 /** Do nothing */
79 public void error(Object message, Throwable t) {
80 }
81
82 /** Do nothing */
83 public void fatal(Object message) {
84 }
85
86 /** Do nothing */
87 public void fatal(Object message, Throwable t) {
88 }
89
90 /**
91 * Debug is never enabled.
92 *
93 * @return false
94 */
95 public final boolean isDebugEnabled() {
96 return false;
97 }
98
99 /**
100 * Error is never enabled.
101 *
102 * @return false
103 */
104 public final boolean isErrorEnabled() {
105 return false;
106 }
107
108 /**
109 * Fatal is never enabled.
110 *
111 * @return false
112 */
113 public final boolean isFatalEnabled() {
114 return false;
115 }
116
117 /**
118 * Info is never enabled.
119 *
120 * @return false
121 */
122 public final boolean isInfoEnabled() {
123 return false;
124 }
125
126 /**
127 * Trace is never enabled.
128 *
129 * @return false
130 */
131 public final boolean isTraceEnabled() {
132 return false;
133 }
134
135 /**
136 * Warn is never enabled.
137 *
138 * @return false
139 */
140 public final boolean isWarnEnabled() {
141 return false;
142 }
143
144 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.Serializable;
19 import org.apache.commons.logging.Log;
20
21 /**
22 * <p>
23 * Trivial implementation of Log that throws away all messages. No configurable
24 * system properties are supported.
25 * </p>
26 *
27 * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
28 * @author Rod Waldhoff
29 * @version $Id: NoOpLog.java,v 1.8 2004/06/06 21:13:12 rdonkin Exp $
30 */
31 public class NoOpLog implements Log, Serializable {
32 private static final long serialVersionUID = 561423906191706148L;
33
34 /** Convenience constructor */
35 public NoOpLog() {
36 }
37
38 /** Base constructor */
39 public NoOpLog(String name) {
40 }
41
42 /** Do nothing */
43 public void trace(Object message) {
44 }
45
46 /** Do nothing */
47 public void trace(Object message, Throwable t) {
48 }
49
50 /** Do nothing */
51 public void debug(Object message) {
52 }
53
54 /** Do nothing */
55 public void debug(Object message, Throwable t) {
56 }
57
58 /** Do nothing */
59 public void info(Object message) {
60 }
61
62 /** Do nothing */
63 public void info(Object message, Throwable t) {
64 }
65
66 /** Do nothing */
67 public void warn(Object message) {
68 }
69
70 /** Do nothing */
71 public void warn(Object message, Throwable t) {
72 }
73
74 /** Do nothing */
75 public void error(Object message) {
76 }
77
78 /** Do nothing */
79 public void error(Object message, Throwable t) {
80 }
81
82 /** Do nothing */
83 public void fatal(Object message) {
84 }
85
86 /** Do nothing */
87 public void fatal(Object message, Throwable t) {
88 }
89
90 /**
91 * Debug is never enabled.
92 *
93 * @return false
94 */
95 public final boolean isDebugEnabled() {
96 return false;
97 }
98
99 /**
100 * Error is never enabled.
101 *
102 * @return false
103 */
104 public final boolean isErrorEnabled() {
105 return false;
106 }
107
108 /**
109 * Fatal is never enabled.
110 *
111 * @return false
112 */
113 public final boolean isFatalEnabled() {
114 return false;
115 }
116
117 /**
118 * Info is never enabled.
119 *
120 * @return false
121 */
122 public final boolean isInfoEnabled() {
123 return false;
124 }
125
126 /**
127 * Trace is never enabled.
128 *
129 * @return false
130 */
131 public final boolean isTraceEnabled() {
132 return false;
133 }
134
135 /**
136 * Warn is never enabled.
137 *
138 * @return false
139 */
140 public final boolean isWarnEnabled() {
141 return false;
142 }
143
144 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.ObjectStreamException;
19 import java.io.Serializable;
20
21 import org.apache.commons.logging.Log;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24 import org.slf4j.spi.LocationAwareLogger;
25
26 /**
27 * Implementation of {@link Log org.apache.commons.logging.Log} interface which
28 * delegates all processing to a wrapped {@link Logger org.slf4j.Logger}
29 * instance.
30 *
31 * <p>
32 * JCL's FATAL level is mapped to ERROR. All other levels map one to one.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class SLF4JLocationAwareLog implements Log, Serializable {
37
38 private static final long serialVersionUID = -2379157579039314822L;
39
40 // used to store this logger's name to recreate it after serialization
41 protected String name;
42
43 // in both Log4jLogger and Jdk14Logger classes in the original JCL, the
44 // logger instance is transient
45 private transient LocationAwareLogger logger;
46
47 private static final String FQCN = SLF4JLocationAwareLog.class.getName();
48
49 SLF4JLocationAwareLog(LocationAwareLogger logger) {
50 this.logger = logger;
51 this.name = logger.getName();
52 }
53
54 /**
55 * Delegates to the <code>isTraceEnabled<code> method of the wrapped
56 * <code>org.slf4j.Logger</code> instance.
57 */
58 public boolean isTraceEnabled() {
59 return logger.isTraceEnabled();
60 }
61
62 /**
63 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
64 */
65 public boolean isDebugEnabled() {
66 return logger.isDebugEnabled();
67 }
68
69 /**
70 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
71 */
72 public boolean isInfoEnabled() {
73 return logger.isInfoEnabled();
74 }
75
76 /**
77 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
78 */
79 public boolean isWarnEnabled() {
80 return logger.isWarnEnabled();
81 }
82
83 /**
84 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
85 */
86 public boolean isErrorEnabled() {
87 return logger.isErrorEnabled();
88 }
89
90 /**
91 * Delegates to the <code>isErrorEnabled<code> method of the wrapped
92 * <code>org.slf4j.Logger</code> instance.
93 */
94 public boolean isFatalEnabled() {
95 return logger.isErrorEnabled();
96 }
97
98 /**
99 * Converts the input parameter to String and then delegates to the debug
100 * method of the wrapped <code>org.slf4j.Logger</code> instance.
101 *
102 * @param message
103 * the message to log. Converted to {@link String}
104 */
105 public void trace(Object message) {
106 logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, null);
107 }
108
109 /**
110 * Converts the first input parameter to String and then delegates to the
111 * debug method of the wrapped <code>org.slf4j.Logger</code> instance.
112 *
113 * @param message
114 * the message to log. Converted to {@link String}
115 * @param t
116 * the exception to log
117 */
118 public void trace(Object message, Throwable t) {
119 logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, t);
120 }
121
122 /**
123 * Converts the input parameter to String and then delegates to the wrapped
124 * <code>org.slf4j.Logger</code> instance.
125 *
126 * @param message
127 * the message to log. Converted to {@link String}
128 */
129 public void debug(Object message) {
130 logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, null);
131 }
132
133 /**
134 * Converts the first input parameter to String and then delegates to the
135 * wrapped <code>org.slf4j.Logger</code> instance.
136 *
137 * @param message
138 * the message to log. Converted to {@link String}
139 * @param t
140 * the exception to log
141 */
142 public void debug(Object message, Throwable t) {
143 logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, t);
144 }
145
146 /**
147 * Converts the input parameter to String and then delegates to the wrapped
148 * <code>org.slf4j.Logger</code> instance.
149 *
150 * @param message
151 * the message to log. Converted to {@link String}
152 */
153 public void info(Object message) {
154 logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, null);
155 }
156
157 /**
158 * Converts the first input parameter to String and then delegates to the
159 * wrapped <code>org.slf4j.Logger</code> instance.
160 *
161 * @param message
162 * the message to log. Converted to {@link String}
163 * @param t
164 * the exception to log
165 */
166 public void info(Object message, Throwable t) {
167 logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, t);
168 }
169
170 /**
171 * Converts the input parameter to String and then delegates to the wrapped
172 * <code>org.slf4j.Logger</code> instance.
173 *
174 * @param message
175 * the message to log. Converted to {@link String}
176 */
177 public void warn(Object message) {
178 logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, null);
179 }
180
181 /**
182 * Converts the first input parameter to String and then delegates to the
183 * wrapped <code>org.slf4j.Logger</code> instance.
184 *
185 * @param message
186 * the message to log. Converted to {@link String}
187 * @param t
188 * the exception to log
189 */
190 public void warn(Object message, Throwable t) {
191 logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, t);
192 }
193
194 /**
195 * Converts the input parameter to String and then delegates to the wrapped
196 * <code>org.slf4j.Logger</code> instance.
197 *
198 * @param message
199 * the message to log. Converted to {@link String}
200 */
201 public void error(Object message) {
202 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null);
203 }
204
205 /**
206 * Converts the first input parameter to String and then delegates to the
207 * wrapped <code>org.slf4j.Logger</code> instance.
208 *
209 * @param message
210 * the message to log. Converted to {@link String}
211 * @param t
212 * the exception to log
213 */
214 public void error(Object message, Throwable t) {
215 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t);
216 }
217
218 /**
219 * Converts the input parameter to String and then delegates to the error
220 * method of the wrapped <code>org.slf4j.Logger</code> instance.
221 *
222 * @param message
223 * the message to log. Converted to {@link String}
224 */
225 public void fatal(Object message) {
226 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null);
227 }
228
229 /**
230 * Converts the first input parameter to String and then delegates to the
231 * error method of the wrapped <code>org.slf4j.Logger</code> instance.
232 *
233 * @param message
234 * the message to log. Converted to {@link String}
235 * @param t
236 * the exception to log
237 */
238 public void fatal(Object message, Throwable t) {
239 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t);
240 }
241
242 /**
243 * Replace this instance with a homonymous (same name) logger returned by
244 * LoggerFactory. Note that this method is only called during deserialization.
245 *
246 * @return logger with same name as returned by LoggerFactory
247 * @throws ObjectStreamException
248 */
249 protected Object readResolve() throws ObjectStreamException {
250 Logger logger = LoggerFactory.getLogger(this.name);
251 return new SLF4JLocationAwareLog((LocationAwareLogger) logger);
252 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.ObjectStreamException;
19 import java.io.Serializable;
20
21 import org.apache.commons.logging.Log;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24 import org.slf4j.spi.LocationAwareLogger;
25
26 /**
27 * Implementation of {@link Log org.apache.commons.logging.Log} interface which
28 * delegates all processing to a wrapped {@link Logger org.slf4j.Logger}
29 * instance.
30 *
31 * <p>
32 * JCL's FATAL level is mapped to ERROR. All other levels map one to one.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class SLF4JLocationAwareLog implements Log, Serializable {
37
38 private static final long serialVersionUID = -2379157579039314822L;
39
40 // used to store this logger's name to recreate it after serialization
41 protected String name;
42
43 // in both Log4jLogger and Jdk14Logger classes in the original JCL, the
44 // logger instance is transient
45 private transient LocationAwareLogger logger;
46
47 private static final String FQCN = SLF4JLocationAwareLog.class.getName();
48
49 SLF4JLocationAwareLog(LocationAwareLogger logger) {
50 this.logger = logger;
51 this.name = logger.getName();
52 }
53
54 /**
55 * Delegates to the <code>isTraceEnabled<code> method of the wrapped
56 * <code>org.slf4j.Logger</code> instance.
57 */
58 public boolean isTraceEnabled() {
59 return logger.isTraceEnabled();
60 }
61
62 /**
63 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
64 */
65 public boolean isDebugEnabled() {
66 return logger.isDebugEnabled();
67 }
68
69 /**
70 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
71 */
72 public boolean isInfoEnabled() {
73 return logger.isInfoEnabled();
74 }
75
76 /**
77 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
78 */
79 public boolean isWarnEnabled() {
80 return logger.isWarnEnabled();
81 }
82
83 /**
84 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
85 */
86 public boolean isErrorEnabled() {
87 return logger.isErrorEnabled();
88 }
89
90 /**
91 * Delegates to the <code>isErrorEnabled<code> method of the wrapped
92 * <code>org.slf4j.Logger</code> instance.
93 */
94 public boolean isFatalEnabled() {
95 return logger.isErrorEnabled();
96 }
97
98 /**
99 * Converts the input parameter to String and then delegates to the debug
100 * method of the wrapped <code>org.slf4j.Logger</code> instance.
101 *
102 * @param message
103 * the message to log. Converted to {@link String}
104 */
105 public void trace(Object message) {
106 logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, null);
107 }
108
109 /**
110 * Converts the first input parameter to String and then delegates to the
111 * debug method of the wrapped <code>org.slf4j.Logger</code> instance.
112 *
113 * @param message
114 * the message to log. Converted to {@link String}
115 * @param t
116 * the exception to log
117 */
118 public void trace(Object message, Throwable t) {
119 logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, t);
120 }
121
122 /**
123 * Converts the input parameter to String and then delegates to the wrapped
124 * <code>org.slf4j.Logger</code> instance.
125 *
126 * @param message
127 * the message to log. Converted to {@link String}
128 */
129 public void debug(Object message) {
130 logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, null);
131 }
132
133 /**
134 * Converts the first input parameter to String and then delegates to the
135 * wrapped <code>org.slf4j.Logger</code> instance.
136 *
137 * @param message
138 * the message to log. Converted to {@link String}
139 * @param t
140 * the exception to log
141 */
142 public void debug(Object message, Throwable t) {
143 logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, t);
144 }
145
146 /**
147 * Converts the input parameter to String and then delegates to the wrapped
148 * <code>org.slf4j.Logger</code> instance.
149 *
150 * @param message
151 * the message to log. Converted to {@link String}
152 */
153 public void info(Object message) {
154 logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, null);
155 }
156
157 /**
158 * Converts the first input parameter to String and then delegates to the
159 * wrapped <code>org.slf4j.Logger</code> instance.
160 *
161 * @param message
162 * the message to log. Converted to {@link String}
163 * @param t
164 * the exception to log
165 */
166 public void info(Object message, Throwable t) {
167 logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, t);
168 }
169
170 /**
171 * Converts the input parameter to String and then delegates to the wrapped
172 * <code>org.slf4j.Logger</code> instance.
173 *
174 * @param message
175 * the message to log. Converted to {@link String}
176 */
177 public void warn(Object message) {
178 logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, null);
179 }
180
181 /**
182 * Converts the first input parameter to String and then delegates to the
183 * wrapped <code>org.slf4j.Logger</code> instance.
184 *
185 * @param message
186 * the message to log. Converted to {@link String}
187 * @param t
188 * the exception to log
189 */
190 public void warn(Object message, Throwable t) {
191 logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, t);
192 }
193
194 /**
195 * Converts the input parameter to String and then delegates to the wrapped
196 * <code>org.slf4j.Logger</code> instance.
197 *
198 * @param message
199 * the message to log. Converted to {@link String}
200 */
201 public void error(Object message) {
202 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null);
203 }
204
205 /**
206 * Converts the first input parameter to String and then delegates to the
207 * wrapped <code>org.slf4j.Logger</code> instance.
208 *
209 * @param message
210 * the message to log. Converted to {@link String}
211 * @param t
212 * the exception to log
213 */
214 public void error(Object message, Throwable t) {
215 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t);
216 }
217
218 /**
219 * Converts the input parameter to String and then delegates to the error
220 * method of the wrapped <code>org.slf4j.Logger</code> instance.
221 *
222 * @param message
223 * the message to log. Converted to {@link String}
224 */
225 public void fatal(Object message) {
226 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null);
227 }
228
229 /**
230 * Converts the first input parameter to String and then delegates to the
231 * error method of the wrapped <code>org.slf4j.Logger</code> instance.
232 *
233 * @param message
234 * the message to log. Converted to {@link String}
235 * @param t
236 * the exception to log
237 */
238 public void fatal(Object message, Throwable t) {
239 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t);
240 }
241
242 /**
243 * Replace this instance with a homonymous (same name) logger returned by
244 * LoggerFactory. Note that this method is only called during deserialization.
245 *
246 * @return logger with same name as returned by LoggerFactory
247 * @throws ObjectStreamException
248 */
249 protected Object readResolve() throws ObjectStreamException {
250 Logger logger = LoggerFactory.getLogger(this.name);
251 return new SLF4JLocationAwareLog((LocationAwareLogger) logger);
252 }
253253 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.ObjectStreamException;
19 import java.io.Serializable;
20
21 import org.apache.commons.logging.Log;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 /**
26 * Implementation of {@link Log org.apache.commons.logging.Log} interface which
27 * delegates all processing to a wrapped {@link Logger org.slf4j.Logger}
28 * instance.
29 *
30 * <p>
31 * JCL's FATAL level is mapped to ERROR. All other levels map one to one.
32 *
33 * @author Ceki G&uuml;lc&uuml;
34 */
35 public class SLF4JLog implements Log, Serializable {
36
37 private static final long serialVersionUID = 680728617011167209L;
38
39 // used to store this logger's name to recreate it after serialization
40 protected String name;
41
42 // in both Log4jLogger and Jdk14Logger classes in the original JCL, the
43 // logger instance is transient
44 private transient Logger logger;
45
46 SLF4JLog(Logger logger) {
47 this.logger = logger;
48 this.name = logger.getName();
49 }
50
51 /**
52 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
53 */
54 public boolean isDebugEnabled() {
55 return logger.isDebugEnabled();
56 }
57
58 /**
59 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
60 */
61 public boolean isErrorEnabled() {
62 return logger.isErrorEnabled();
63 }
64
65 /**
66 * Delegates to the <code>isErrorEnabled<code> method of the wrapped
67 * <code>org.slf4j.Logger</code> instance.
68 */
69 public boolean isFatalEnabled() {
70 return logger.isErrorEnabled();
71 }
72
73 /**
74 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
75 */
76 public boolean isInfoEnabled() {
77 return logger.isInfoEnabled();
78 }
79
80 /**
81 * Delegates to the <code>isDebugEnabled<code> method of the wrapped
82 * <code>org.slf4j.Logger</code> instance.
83 */
84 public boolean isTraceEnabled() {
85 return logger.isTraceEnabled();
86 }
87
88 /**
89 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
90 */
91 public boolean isWarnEnabled() {
92 return logger.isWarnEnabled();
93 }
94
95 /**
96 * Converts the input parameter to String and then delegates to the debug
97 * method of the wrapped <code>org.slf4j.Logger</code> instance.
98 *
99 * @param message
100 * the message to log. Converted to {@link String}
101 */
102 public void trace(Object message) {
103 logger.trace(String.valueOf(message));
104 }
105
106 /**
107 * Converts the first input parameter to String and then delegates to the
108 * debug method of the wrapped <code>org.slf4j.Logger</code> instance.
109 *
110 * @param message
111 * the message to log. Converted to {@link String}
112 * @param t
113 * the exception to log
114 */
115 public void trace(Object message, Throwable t) {
116 logger.trace(String.valueOf(message), t);
117 }
118
119 /**
120 * Converts the input parameter to String and then delegates to the wrapped
121 * <code>org.slf4j.Logger</code> instance.
122 *
123 * @param message
124 * the message to log. Converted to {@link String}
125 */
126 public void debug(Object message) {
127 logger.debug(String.valueOf(message));
128 }
129
130 /**
131 * Converts the first input parameter to String and then delegates to the
132 * wrapped <code>org.slf4j.Logger</code> instance.
133 *
134 * @param message
135 * the message to log. Converted to {@link String}
136 * @param t
137 * the exception to log
138 */
139 public void debug(Object message, Throwable t) {
140 logger.debug(String.valueOf(message), t);
141 }
142
143 /**
144 * Converts the input parameter to String and then delegates to the wrapped
145 * <code>org.slf4j.Logger</code> instance.
146 *
147 * @param message
148 * the message to log. Converted to {@link String}
149 */
150 public void info(Object message) {
151 logger.info(String.valueOf(message));
152 }
153
154 /**
155 * Converts the first input parameter to String and then delegates to the
156 * wrapped <code>org.slf4j.Logger</code> instance.
157 *
158 * @param message
159 * the message to log. Converted to {@link String}
160 * @param t
161 * the exception to log
162 */
163 public void info(Object message, Throwable t) {
164 logger.info(String.valueOf(message), t);
165 }
166
167 /**
168 * Converts the input parameter to String and then delegates to the wrapped
169 * <code>org.slf4j.Logger</code> instance.
170 *
171 * @param message
172 * the message to log. Converted to {@link String}
173 */
174 public void warn(Object message) {
175 logger.warn(String.valueOf(message));
176 }
177
178 /**
179 * Converts the first input parameter to String and then delegates to the
180 * wrapped <code>org.slf4j.Logger</code> instance.
181 *
182 * @param message
183 * the message to log. Converted to {@link String}
184 * @param t
185 * the exception to log
186 */
187 public void warn(Object message, Throwable t) {
188 logger.warn(String.valueOf(message), t);
189 }
190
191 /**
192 * Converts the input parameter to String and then delegates to the wrapped
193 * <code>org.slf4j.Logger</code> instance.
194 *
195 * @param message
196 * the message to log. Converted to {@link String}
197 */
198 public void error(Object message) {
199 logger.error(String.valueOf(message));
200 }
201
202 /**
203 * Converts the first input parameter to String and then delegates to the
204 * wrapped <code>org.slf4j.Logger</code> instance.
205 *
206 * @param message
207 * the message to log. Converted to {@link String}
208 * @param t
209 * the exception to log
210 */
211 public void error(Object message, Throwable t) {
212 logger.error(String.valueOf(message), t);
213 }
214
215 /**
216 * Converts the input parameter to String and then delegates to the error
217 * method of the wrapped <code>org.slf4j.Logger</code> instance.
218 *
219 * @param message
220 * the message to log. Converted to {@link String}
221 */
222 public void fatal(Object message) {
223 logger.error(String.valueOf(message));
224 }
225
226 /**
227 * Converts the first input parameter to String and then delegates to the
228 * error method of the wrapped <code>org.slf4j.Logger</code> instance.
229 *
230 * @param message
231 * the message to log. Converted to {@link String}
232 * @param t
233 * the exception to log
234 */
235 public void fatal(Object message, Throwable t) {
236 logger.error(String.valueOf(message), t);
237 }
238
239 /**
240 * Replace this instance with a homonymous (same name) logger returned by
241 * LoggerFactory. Note that this method is only called during deserialization.
242 *
243 * @return logger with same name as returned by LoggerFactory
244 * @throws ObjectStreamException
245 */
246 protected Object readResolve() throws ObjectStreamException {
247 Logger logger = LoggerFactory.getLogger(this.name);
248 return new SLF4JLog(logger);
249 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.ObjectStreamException;
19 import java.io.Serializable;
20
21 import org.apache.commons.logging.Log;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 /**
26 * Implementation of {@link Log org.apache.commons.logging.Log} interface which
27 * delegates all processing to a wrapped {@link Logger org.slf4j.Logger}
28 * instance.
29 *
30 * <p>
31 * JCL's FATAL level is mapped to ERROR. All other levels map one to one.
32 *
33 * @author Ceki G&uuml;lc&uuml;
34 */
35 public class SLF4JLog implements Log, Serializable {
36
37 private static final long serialVersionUID = 680728617011167209L;
38
39 // used to store this logger's name to recreate it after serialization
40 protected String name;
41
42 // in both Log4jLogger and Jdk14Logger classes in the original JCL, the
43 // logger instance is transient
44 private transient Logger logger;
45
46 SLF4JLog(Logger logger) {
47 this.logger = logger;
48 this.name = logger.getName();
49 }
50
51 /**
52 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
53 */
54 public boolean isDebugEnabled() {
55 return logger.isDebugEnabled();
56 }
57
58 /**
59 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
60 */
61 public boolean isErrorEnabled() {
62 return logger.isErrorEnabled();
63 }
64
65 /**
66 * Delegates to the <code>isErrorEnabled<code> method of the wrapped
67 * <code>org.slf4j.Logger</code> instance.
68 */
69 public boolean isFatalEnabled() {
70 return logger.isErrorEnabled();
71 }
72
73 /**
74 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
75 */
76 public boolean isInfoEnabled() {
77 return logger.isInfoEnabled();
78 }
79
80 /**
81 * Delegates to the <code>isDebugEnabled<code> method of the wrapped
82 * <code>org.slf4j.Logger</code> instance.
83 */
84 public boolean isTraceEnabled() {
85 return logger.isTraceEnabled();
86 }
87
88 /**
89 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
90 */
91 public boolean isWarnEnabled() {
92 return logger.isWarnEnabled();
93 }
94
95 /**
96 * Converts the input parameter to String and then delegates to the debug
97 * method of the wrapped <code>org.slf4j.Logger</code> instance.
98 *
99 * @param message
100 * the message to log. Converted to {@link String}
101 */
102 public void trace(Object message) {
103 logger.trace(String.valueOf(message));
104 }
105
106 /**
107 * Converts the first input parameter to String and then delegates to the
108 * debug method of the wrapped <code>org.slf4j.Logger</code> instance.
109 *
110 * @param message
111 * the message to log. Converted to {@link String}
112 * @param t
113 * the exception to log
114 */
115 public void trace(Object message, Throwable t) {
116 logger.trace(String.valueOf(message), t);
117 }
118
119 /**
120 * Converts the input parameter to String and then delegates to the wrapped
121 * <code>org.slf4j.Logger</code> instance.
122 *
123 * @param message
124 * the message to log. Converted to {@link String}
125 */
126 public void debug(Object message) {
127 logger.debug(String.valueOf(message));
128 }
129
130 /**
131 * Converts the first input parameter to String and then delegates to the
132 * wrapped <code>org.slf4j.Logger</code> instance.
133 *
134 * @param message
135 * the message to log. Converted to {@link String}
136 * @param t
137 * the exception to log
138 */
139 public void debug(Object message, Throwable t) {
140 logger.debug(String.valueOf(message), t);
141 }
142
143 /**
144 * Converts the input parameter to String and then delegates to the wrapped
145 * <code>org.slf4j.Logger</code> instance.
146 *
147 * @param message
148 * the message to log. Converted to {@link String}
149 */
150 public void info(Object message) {
151 logger.info(String.valueOf(message));
152 }
153
154 /**
155 * Converts the first input parameter to String and then delegates to the
156 * wrapped <code>org.slf4j.Logger</code> instance.
157 *
158 * @param message
159 * the message to log. Converted to {@link String}
160 * @param t
161 * the exception to log
162 */
163 public void info(Object message, Throwable t) {
164 logger.info(String.valueOf(message), t);
165 }
166
167 /**
168 * Converts the input parameter to String and then delegates to the wrapped
169 * <code>org.slf4j.Logger</code> instance.
170 *
171 * @param message
172 * the message to log. Converted to {@link String}
173 */
174 public void warn(Object message) {
175 logger.warn(String.valueOf(message));
176 }
177
178 /**
179 * Converts the first input parameter to String and then delegates to the
180 * wrapped <code>org.slf4j.Logger</code> instance.
181 *
182 * @param message
183 * the message to log. Converted to {@link String}
184 * @param t
185 * the exception to log
186 */
187 public void warn(Object message, Throwable t) {
188 logger.warn(String.valueOf(message), t);
189 }
190
191 /**
192 * Converts the input parameter to String and then delegates to the wrapped
193 * <code>org.slf4j.Logger</code> instance.
194 *
195 * @param message
196 * the message to log. Converted to {@link String}
197 */
198 public void error(Object message) {
199 logger.error(String.valueOf(message));
200 }
201
202 /**
203 * Converts the first input parameter to String and then delegates to the
204 * wrapped <code>org.slf4j.Logger</code> instance.
205 *
206 * @param message
207 * the message to log. Converted to {@link String}
208 * @param t
209 * the exception to log
210 */
211 public void error(Object message, Throwable t) {
212 logger.error(String.valueOf(message), t);
213 }
214
215 /**
216 * Converts the input parameter to String and then delegates to the error
217 * method of the wrapped <code>org.slf4j.Logger</code> instance.
218 *
219 * @param message
220 * the message to log. Converted to {@link String}
221 */
222 public void fatal(Object message) {
223 logger.error(String.valueOf(message));
224 }
225
226 /**
227 * Converts the first input parameter to String and then delegates to the
228 * error method of the wrapped <code>org.slf4j.Logger</code> instance.
229 *
230 * @param message
231 * the message to log. Converted to {@link String}
232 * @param t
233 * the exception to log
234 */
235 public void fatal(Object message, Throwable t) {
236 logger.error(String.valueOf(message), t);
237 }
238
239 /**
240 * Replace this instance with a homonymous (same name) logger returned by
241 * LoggerFactory. Note that this method is only called during deserialization.
242 *
243 * @return logger with same name as returned by LoggerFactory
244 * @throws ObjectStreamException
245 */
246 protected Object readResolve() throws ObjectStreamException {
247 Logger logger = LoggerFactory.getLogger(this.name);
248 return new SLF4JLog(logger);
249 }
250250 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogConfigurationException;
20 import org.apache.commons.logging.LogFactory;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23 import org.slf4j.spi.LocationAwareLogger;
24
25 import java.util.ArrayList;
26 import java.util.Enumeration;
27 import java.util.Hashtable;
28 import java.util.List;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31
32 /**
33 * <p>
34 * Concrete subclass of {@link LogFactory} which always delegates to the
35 * {@link LoggerFactory org.slf4j.LoggerFactory} class.
36 *
37 * <p>
38 * This factory generates instances of {@link SLF4JLog}. It will remember
39 * previously created instances for the same name, and will return them on
40 * repeated requests to the <code>getInstance()</code> method.
41 *
42 * <p>
43 * This implementation ignores any configured attributes.
44 * </p>
45 *
46 * @author Rod Waldhoff
47 * @author Craig R. McClanahan
48 * @author Richard A. Sitze
49 * @author Ceki G&uuml;lc&uuml;
50 */
51 @SuppressWarnings("rawtypes")
52 public class SLF4JLogFactory extends LogFactory {
53
54 // ----------------------------------------------------------- Constructors
55
56 /**
57 * The {@link org.apache.commons.logging.Log}instances that have already been
58 * created, keyed by logger name.
59 */
60 ConcurrentMap<String, Log> loggerMap;
61
62 /**
63 * Public no-arguments constructor required by the lookup mechanism.
64 */
65 public SLF4JLogFactory() {
66 loggerMap = new ConcurrentHashMap<String, Log>();
67 }
68
69 // ----------------------------------------------------- Manifest Constants
70
71 /**
72 * The name of the system property identifying our {@link Log}implementation
73 * class.
74 */
75 public static final String LOG_PROPERTY = "org.apache.commons.logging.Log";
76
77 // ----------------------------------------------------- Instance Variables
78
79 /**
80 * Configuration attributes.
81 */
82 protected Hashtable attributes = new Hashtable();
83
84 // --------------------------------------------------------- Public Methods
85
86 /**
87 * Return the configuration attribute with the specified name (if any), or
88 * <code>null</code> if there is no such attribute.
89 *
90 * @param name
91 * Name of the attribute to return
92 */
93 public Object getAttribute(String name) {
94
95 return (attributes.get(name));
96
97 }
98
99 /**
100 * Return an array containing the names of all currently defined configuration
101 * attributes. If there are no such attributes, a zero length array is
102 * returned.
103 */
104 @SuppressWarnings("unchecked")
105 public String[] getAttributeNames() {
106
107 List<String> names = new ArrayList<String>();
108 Enumeration<String> keys = attributes.keys();
109 while (keys.hasMoreElements()) {
110 names.add((String) keys.nextElement());
111 }
112 String results[] = new String[names.size()];
113 for (int i = 0; i < results.length; i++) {
114 results[i] = (String) names.get(i);
115 }
116 return (results);
117
118 }
119
120 /**
121 * Convenience method to derive a name from the specified class and call
122 * <code>getInstance(String)</code> with it.
123 *
124 * @param clazz
125 * Class for which a suitable Log name will be derived
126 *
127 * @exception LogConfigurationException
128 * if a suitable <code>Log</code> instance cannot be returned
129 */
130 public Log getInstance(Class clazz) throws LogConfigurationException {
131 return (getInstance(clazz.getName()));
132 }
133
134 /**
135 * <p>
136 * Construct (if necessary) and return a <code>Log</code> instance, using
137 * the factory's current set of configuration attributes.
138 * </p>
139 *
140 * @param name
141 * Logical name of the <code>Log</code> instance to be returned
142 * (the meaning of this name is only known to the underlying logging
143 * implementation that is being wrapped)
144 *
145 * @exception LogConfigurationException
146 * if a suitable <code>Log</code> instance cannot be returned
147 */
148 public Log getInstance(String name) throws LogConfigurationException {
149 Log instance = loggerMap.get(name);
150 if (instance != null) {
151 return instance;
152 } else {
153 Log newInstance;
154 Logger slf4jLogger = LoggerFactory.getLogger(name);
155 if (slf4jLogger instanceof LocationAwareLogger) {
156 newInstance = new SLF4JLocationAwareLog((LocationAwareLogger) slf4jLogger);
157 } else {
158 newInstance = new SLF4JLog(slf4jLogger);
159 }
160 Log oldInstance = loggerMap.putIfAbsent(name, newInstance);
161 return oldInstance == null ? newInstance : oldInstance;
162 }
163 }
164
165 /**
166 * Release any internal references to previously created
167 * {@link org.apache.commons.logging.Log}instances returned by this factory.
168 * This is useful in environments like servlet containers, which implement
169 * application reloading by throwing away a ClassLoader. Dangling references
170 * to objects in that class loader would prevent garbage collection.
171 */
172 public void release() {
173 // This method is never called by jcl-over-slf4j classes. However,
174 // in certain deployment scenarios, in particular if jcl-over-slf4j.jar
175 // is
176 // in the the web-app class loader and the official commons-logging.jar is
177 // deployed in some parent class loader (e.g. commons/lib), then it is
178 // possible
179 // for the parent class loader to mask the classes shipping in
180 // jcl-over-slf4j.jar.
181 System.out.println("WARN: The method " + SLF4JLogFactory.class + "#release() was invoked.");
182 System.out.println("WARN: Please see http://www.slf4j.org/codes.html#release for an explanation.");
183 System.out.flush();
184 }
185
186 /**
187 * Remove any configuration attribute associated with the specified name. If
188 * there is no such attribute, no action is taken.
189 *
190 * @param name
191 * Name of the attribute to remove
192 */
193 public void removeAttribute(String name) {
194 attributes.remove(name);
195 }
196
197 /**
198 * Set the configuration attribute with the specified name. Calling this with
199 * a <code>null</code> value is equivalent to calling
200 * <code>removeAttribute(name)</code>.
201 *
202 * @param name
203 * Name of the attribute to set
204 * @param value
205 * Value of the attribute to set, or <code>null</code> to remove
206 * any setting for this attribute
207 */
208 @SuppressWarnings("unchecked")
209 public void setAttribute(String name, Object value) {
210
211 if (value == null) {
212 attributes.remove(name);
213 } else {
214 attributes.put(name, value);
215 }
216
217 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogConfigurationException;
20 import org.apache.commons.logging.LogFactory;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23 import org.slf4j.spi.LocationAwareLogger;
24
25 import java.util.ArrayList;
26 import java.util.Enumeration;
27 import java.util.Hashtable;
28 import java.util.List;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31
32 /**
33 * <p>
34 * Concrete subclass of {@link LogFactory} which always delegates to the
35 * {@link LoggerFactory org.slf4j.LoggerFactory} class.
36 *
37 * <p>
38 * This factory generates instances of {@link SLF4JLog}. It will remember
39 * previously created instances for the same name, and will return them on
40 * repeated requests to the <code>getInstance()</code> method.
41 *
42 * <p>
43 * This implementation ignores any configured attributes.
44 * </p>
45 *
46 * @author Rod Waldhoff
47 * @author Craig R. McClanahan
48 * @author Richard A. Sitze
49 * @author Ceki G&uuml;lc&uuml;
50 */
51 @SuppressWarnings("rawtypes")
52 public class SLF4JLogFactory extends LogFactory {
53
54 // ----------------------------------------------------------- Constructors
55
56 /**
57 * The {@link org.apache.commons.logging.Log}instances that have already been
58 * created, keyed by logger name.
59 */
60 ConcurrentMap<String, Log> loggerMap;
61
62 /**
63 * Public no-arguments constructor required by the lookup mechanism.
64 */
65 public SLF4JLogFactory() {
66 loggerMap = new ConcurrentHashMap<String, Log>();
67 }
68
69 // ----------------------------------------------------- Manifest Constants
70
71 /**
72 * The name of the system property identifying our {@link Log}implementation
73 * class.
74 */
75 public static final String LOG_PROPERTY = "org.apache.commons.logging.Log";
76
77 // ----------------------------------------------------- Instance Variables
78
79 /**
80 * Configuration attributes.
81 */
82 protected Hashtable attributes = new Hashtable();
83
84 // --------------------------------------------------------- Public Methods
85
86 /**
87 * Return the configuration attribute with the specified name (if any), or
88 * <code>null</code> if there is no such attribute.
89 *
90 * @param name
91 * Name of the attribute to return
92 */
93 public Object getAttribute(String name) {
94
95 return (attributes.get(name));
96
97 }
98
99 /**
100 * Return an array containing the names of all currently defined configuration
101 * attributes. If there are no such attributes, a zero length array is
102 * returned.
103 */
104 @SuppressWarnings("unchecked")
105 public String[] getAttributeNames() {
106
107 List<String> names = new ArrayList<String>();
108 Enumeration<String> keys = attributes.keys();
109 while (keys.hasMoreElements()) {
110 names.add((String) keys.nextElement());
111 }
112 String results[] = new String[names.size()];
113 for (int i = 0; i < results.length; i++) {
114 results[i] = (String) names.get(i);
115 }
116 return (results);
117
118 }
119
120 /**
121 * Convenience method to derive a name from the specified class and call
122 * <code>getInstance(String)</code> with it.
123 *
124 * @param clazz
125 * Class for which a suitable Log name will be derived
126 *
127 * @exception LogConfigurationException
128 * if a suitable <code>Log</code> instance cannot be returned
129 */
130 public Log getInstance(Class clazz) throws LogConfigurationException {
131 return (getInstance(clazz.getName()));
132 }
133
134 /**
135 * <p>
136 * Construct (if necessary) and return a <code>Log</code> instance, using
137 * the factory's current set of configuration attributes.
138 * </p>
139 *
140 * @param name
141 * Logical name of the <code>Log</code> instance to be returned
142 * (the meaning of this name is only known to the underlying logging
143 * implementation that is being wrapped)
144 *
145 * @exception LogConfigurationException
146 * if a suitable <code>Log</code> instance cannot be returned
147 */
148 public Log getInstance(String name) throws LogConfigurationException {
149 Log instance = loggerMap.get(name);
150 if (instance != null) {
151 return instance;
152 } else {
153 Log newInstance;
154 Logger slf4jLogger = LoggerFactory.getLogger(name);
155 if (slf4jLogger instanceof LocationAwareLogger) {
156 newInstance = new SLF4JLocationAwareLog((LocationAwareLogger) slf4jLogger);
157 } else {
158 newInstance = new SLF4JLog(slf4jLogger);
159 }
160 Log oldInstance = loggerMap.putIfAbsent(name, newInstance);
161 return oldInstance == null ? newInstance : oldInstance;
162 }
163 }
164
165 /**
166 * Release any internal references to previously created
167 * {@link org.apache.commons.logging.Log}instances returned by this factory.
168 * This is useful in environments like servlet containers, which implement
169 * application reloading by throwing away a ClassLoader. Dangling references
170 * to objects in that class loader would prevent garbage collection.
171 */
172 public void release() {
173 // This method is never called by jcl-over-slf4j classes. However,
174 // in certain deployment scenarios, in particular if jcl-over-slf4j.jar
175 // is
176 // in the the web-app class loader and the official commons-logging.jar is
177 // deployed in some parent class loader (e.g. commons/lib), then it is
178 // possible
179 // for the parent class loader to mask the classes shipping in
180 // jcl-over-slf4j.jar.
181 System.out.println("WARN: The method " + SLF4JLogFactory.class + "#release() was invoked.");
182 System.out.println("WARN: Please see http://www.slf4j.org/codes.html#release for an explanation.");
183 System.out.flush();
184 }
185
186 /**
187 * Remove any configuration attribute associated with the specified name. If
188 * there is no such attribute, no action is taken.
189 *
190 * @param name
191 * Name of the attribute to remove
192 */
193 public void removeAttribute(String name) {
194 attributes.remove(name);
195 }
196
197 /**
198 * Set the configuration attribute with the specified name. Calling this with
199 * a <code>null</code> value is equivalent to calling
200 * <code>removeAttribute(name)</code>.
201 *
202 * @param name
203 * Name of the attribute to set
204 * @param value
205 * Value of the attribute to set, or <code>null</code> to remove
206 * any setting for this attribute
207 */
208 @SuppressWarnings("unchecked")
209 public void setAttribute(String name, Object value) {
210
211 if (value == null) {
212 attributes.remove(name);
213 } else {
214 attributes.put(name, value);
215 }
216
217 }
218218 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.InputStream;
19 import java.io.Serializable;
20 import java.lang.reflect.InvocationTargetException;
21 import java.lang.reflect.Method;
22 import java.security.AccessController;
23 import java.security.PrivilegedAction;
24 import java.text.DateFormat;
25 import java.text.SimpleDateFormat;
26 import java.util.Date;
27 import java.util.Properties;
28
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogConfigurationException;
31
32 /**
33 * <p>
34 * Simple implementation of Log that sends all enabled log messages, for all
35 * defined loggers, to System.err. The following system properties are supported
36 * to configure the behavior of this logger:
37 * </p>
38 * <ul>
39 * <li><code>org.apache.commons.logging.simplelog.defaultlog</code> - Default
40 * logging detail level for all instances of SimpleLog. Must be one of ("trace",
41 * "debug", "info", "warn", "error", or "fatal"). If not specified, defaults to
42 * "info".</li>
43 * <li><code>org.apache.commons.logging.simplelog.log.xxxxx</code> - Logging
44 * detail level for a SimpleLog instance named "xxxxx". Must be one of ("trace",
45 * "debug", "info", "warn", "error", or "fatal"). If not specified, the default
46 * logging detail level is used.</li>
47 * <li><code>org.apache.commons.logging.simplelog.showlogname</code> - Set to
48 * <code>true</code> if you want the Log instance name to be included in output
49 * messages. Defaults to <code>false</code>.</li>
50 * <li><code>org.apache.commons.logging.simplelog.showShortLogname</code> - Set
51 * to <code>true</code> if you want the last component of the name to be
52 * included in output messages. Defaults to <code>true</code>.</li>
53 * <li><code>org.apache.commons.logging.simplelog.showdatetime</code> - Set to
54 * <code>true</code> if you want the current date and time to be included in
55 * output messages. Default is <code>false</code>.</li>
56 * <li><code>org.apache.commons.logging.simplelog.dateTimeFormat</code> - The
57 * date and time format to be used in the output messages. The pattern
58 * describing the date and time format is the same that is used in
59 * <code>java.text.SimpleDateFormat</code>. If the format is not specified or is
60 * invalid, the default format is used. The default format is
61 * <code>yyyy/MM/dd HH:mm:ss:SSS zzz</code>.</li>
62 * </ul>
63 *
64 * <p>
65 * In addition to looking for system properties with the names specified above,
66 * this implementation also checks for a class loader resource named
67 * <code>"simplelog.properties"</code>, and includes any matching definitions
68 * from this resource (if it exists).
69 * </p>
70 *
71 * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
72 * @author Rod Waldhoff
73 * @author Robert Burrell Donkin
74 *
75 * @version $Id: SimpleLog.java,v 1.21 2004/06/06 20:47:56 rdonkin Exp $
76 */
77 public class SimpleLog implements Log, Serializable {
78
79 private static final long serialVersionUID = 136942970684951178L;
80
81 // ------------------------------------------------------- Class Attributes
82
83 /** All system properties used by <code>SimpleLog</code> start with this */
84 static protected final String systemPrefix = "org.apache.commons.logging.simplelog.";
85
86 /** Properties loaded from simplelog.properties */
87 static protected final Properties simpleLogProps = new Properties();
88
89 /** The default format to use when formatting dates */
90 static protected final String DEFAULT_DATE_TIME_FORMAT = "yyyy/MM/dd HH:mm:ss:SSS zzz";
91
92 /** Include the instance name in the log message? */
93 static protected boolean showLogName = false;
94 /**
95 * Include the short name ( last component ) of the logger in the log message.
96 * Defaults to true - otherwise we'll be lost in a flood of messages without
97 * knowing who sends them.
98 */
99 static protected boolean showShortName = true;
100 /** Include the current time in the log message */
101 static protected boolean showDateTime = false;
102 /** The date and time format to use in the log message */
103 static protected String dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
104 /** Used to format times */
105 static protected DateFormat dateFormatter = null;
106
107 // ---------------------------------------------------- Log Level Constants
108
109 /** "Trace" level logging. */
110 public static final int LOG_LEVEL_TRACE = 1;
111 /** "Debug" level logging. */
112 public static final int LOG_LEVEL_DEBUG = 2;
113 /** "Info" level logging. */
114 public static final int LOG_LEVEL_INFO = 3;
115 /** "Warn" level logging. */
116 public static final int LOG_LEVEL_WARN = 4;
117 /** "Error" level logging. */
118 public static final int LOG_LEVEL_ERROR = 5;
119 /** "Fatal" level logging. */
120 public static final int LOG_LEVEL_FATAL = 6;
121
122 /** Enable all logging levels */
123 public static final int LOG_LEVEL_ALL = (LOG_LEVEL_TRACE - 1);
124
125 /** Enable no logging levels */
126 public static final int LOG_LEVEL_OFF = (LOG_LEVEL_FATAL + 1);
127
128 // ------------------------------------------------------------ Initializer
129
130 private static String getStringProperty(String name) {
131 String prop = null;
132 try {
133 prop = System.getProperty(name);
134 } catch (SecurityException e) {
135 ; // Ignore
136 }
137 return (prop == null) ? simpleLogProps.getProperty(name) : prop;
138 }
139
140 private static String getStringProperty(String name, String dephault) {
141 String prop = getStringProperty(name);
142 return (prop == null) ? dephault : prop;
143 }
144
145 private static boolean getBooleanProperty(String name, boolean dephault) {
146 String prop = getStringProperty(name);
147 return (prop == null) ? dephault : "true".equalsIgnoreCase(prop);
148 }
149
150 // Initialize class attributes.
151 // Load properties file, if found.
152 // Override with system properties.
153 static {
154 // Add props from the resource simplelog.properties
155 InputStream in = getResourceAsStream("simplelog.properties");
156 if (null != in) {
157 try {
158 simpleLogProps.load(in);
159 } catch (java.io.IOException e) {
160 // ignored
161 } finally {
162 try {
163 in.close();
164 } catch (java.io.IOException e) {
165 // ignored
166 }
167 }
168 }
169
170 showLogName = getBooleanProperty(systemPrefix + "showlogname", showLogName);
171 showShortName = getBooleanProperty(systemPrefix + "showShortLogname", showShortName);
172 showDateTime = getBooleanProperty(systemPrefix + "showdatetime", showDateTime);
173
174 if (showDateTime) {
175 dateTimeFormat = getStringProperty(systemPrefix + "dateTimeFormat", dateTimeFormat);
176 try {
177 dateFormatter = new SimpleDateFormat(dateTimeFormat);
178 } catch (IllegalArgumentException e) {
179 // If the format pattern is invalid - use the default format
180 dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
181 dateFormatter = new SimpleDateFormat(dateTimeFormat);
182 }
183 }
184 }
185
186 // ------------------------------------------------------------- Attributes
187
188 /** The name of this simple log instance */
189 protected String logName = null;
190 /** The current log level */
191 protected int currentLogLevel;
192 /** The short name of this simple log instance */
193 private String shortLogName = null;
194
195 // ------------------------------------------------------------ Constructor
196
197 /**
198 * Construct a simple log with given name.
199 *
200 * @param name
201 * log name
202 */
203 public SimpleLog(String name) {
204
205 logName = name;
206
207 // Set initial log level
208 // Used to be: set default log level to ERROR
209 // IMHO it should be lower, but at least info ( costin ).
210 setLevel(SimpleLog.LOG_LEVEL_INFO);
211
212 // Set log level from properties
213 String lvl = getStringProperty(systemPrefix + "log." + logName);
214 int i = String.valueOf(name).lastIndexOf(".");
215 while (null == lvl && i > -1) {
216 name = name.substring(0, i);
217 lvl = getStringProperty(systemPrefix + "log." + name);
218 i = String.valueOf(name).lastIndexOf(".");
219 }
220
221 if (null == lvl) {
222 lvl = getStringProperty(systemPrefix + "defaultlog");
223 }
224
225 if ("all".equalsIgnoreCase(lvl)) {
226 setLevel(SimpleLog.LOG_LEVEL_ALL);
227 } else if ("trace".equalsIgnoreCase(lvl)) {
228 setLevel(SimpleLog.LOG_LEVEL_TRACE);
229 } else if ("debug".equalsIgnoreCase(lvl)) {
230 setLevel(SimpleLog.LOG_LEVEL_DEBUG);
231 } else if ("info".equalsIgnoreCase(lvl)) {
232 setLevel(SimpleLog.LOG_LEVEL_INFO);
233 } else if ("warn".equalsIgnoreCase(lvl)) {
234 setLevel(SimpleLog.LOG_LEVEL_WARN);
235 } else if ("error".equalsIgnoreCase(lvl)) {
236 setLevel(SimpleLog.LOG_LEVEL_ERROR);
237 } else if ("fatal".equalsIgnoreCase(lvl)) {
238 setLevel(SimpleLog.LOG_LEVEL_FATAL);
239 } else if ("off".equalsIgnoreCase(lvl)) {
240 setLevel(SimpleLog.LOG_LEVEL_OFF);
241 }
242
243 }
244
245 // -------------------------------------------------------- Properties
246
247 /**
248 * <p>
249 * Set logging level.
250 * </p>
251 *
252 * @param currentLogLevel
253 * new logging level
254 */
255 public void setLevel(int currentLogLevel) {
256
257 this.currentLogLevel = currentLogLevel;
258
259 }
260
261 /**
262 * <p>
263 * Get logging level.
264 * </p>
265 */
266 public int getLevel() {
267
268 return currentLogLevel;
269 }
270
271 // -------------------------------------------------------- Logging Methods
272
273 /**
274 * <p>
275 * Do the actual logging. This method assembles the message and then calls
276 * <code>write()</code> to cause it to be written.
277 * </p>
278 *
279 * @param type
280 * One of the LOG_LEVEL_XXX constants defining the log level
281 * @param message
282 * The message itself (typically a String)
283 * @param t
284 * The exception whose stack trace should be logged
285 */
286 protected void log(int type, Object message, Throwable t) {
287 // Use a string buffer for better performance
288 StringBuffer buf = new StringBuffer();
289
290 // Append date-time if so configured
291 if (showDateTime) {
292 buf.append(dateFormatter.format(new Date()));
293 buf.append(" ");
294 }
295
296 // Append a readable representation of the log level
297 switch (type) {
298 case SimpleLog.LOG_LEVEL_TRACE:
299 buf.append("[TRACE] ");
300 break;
301 case SimpleLog.LOG_LEVEL_DEBUG:
302 buf.append("[DEBUG] ");
303 break;
304 case SimpleLog.LOG_LEVEL_INFO:
305 buf.append("[INFO] ");
306 break;
307 case SimpleLog.LOG_LEVEL_WARN:
308 buf.append("[WARN] ");
309 break;
310 case SimpleLog.LOG_LEVEL_ERROR:
311 buf.append("[ERROR] ");
312 break;
313 case SimpleLog.LOG_LEVEL_FATAL:
314 buf.append("[FATAL] ");
315 break;
316 }
317
318 // Append the name of the log instance if so configured
319 if (showShortName) {
320 if (shortLogName == null) {
321 // Cut all but the last component of the name for both styles
322 shortLogName = logName.substring(logName.lastIndexOf(".") + 1);
323 shortLogName = shortLogName.substring(shortLogName.lastIndexOf("/") + 1);
324 }
325 buf.append(String.valueOf(shortLogName)).append(" - ");
326 } else if (showLogName) {
327 buf.append(String.valueOf(logName)).append(" - ");
328 }
329
330 // Append the message
331 buf.append(String.valueOf(message));
332
333 // Append stack trace if not null
334 if (t != null) {
335 buf.append(" <");
336 buf.append(t.toString());
337 buf.append(">");
338
339 java.io.StringWriter sw = new java.io.StringWriter(1024);
340 java.io.PrintWriter pw = new java.io.PrintWriter(sw);
341 t.printStackTrace(pw);
342 pw.close();
343 buf.append(sw.toString());
344 }
345
346 // Print to the appropriate destination
347 write(buf);
348
349 }
350
351 /**
352 * <p>
353 * Write the content of the message accumulated in the specified
354 * <code>StringBuffer</code> to the appropriate output destination. The
355 * default implementation writes to <code>System.err</code>.
356 * </p>
357 *
358 * @param buffer
359 * A <code>StringBuffer</code> containing the accumulated text to be
360 * logged
361 */
362 protected void write(StringBuffer buffer) {
363
364 System.err.println(buffer.toString());
365
366 }
367
368 /**
369 * Is the given log level currently enabled?
370 *
371 * @param logLevel
372 * is this level enabled?
373 */
374 protected boolean isLevelEnabled(int logLevel) {
375 // log level are numerically ordered so can use simple numeric
376 // comparison
377 return (logLevel >= currentLogLevel);
378 }
379
380 // -------------------------------------------------------- Log Implementation
381
382 /**
383 * <p>
384 * Log a message with debug log level.
385 * </p>
386 */
387 public final void debug(Object message) {
388
389 if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
390 log(SimpleLog.LOG_LEVEL_DEBUG, message, null);
391 }
392 }
393
394 /**
395 * <p>
396 * Log an error with debug log level.
397 * </p>
398 */
399 public final void debug(Object message, Throwable t) {
400
401 if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
402 log(SimpleLog.LOG_LEVEL_DEBUG, message, t);
403 }
404 }
405
406 /**
407 * <p>
408 * Log a message with trace log level.
409 * </p>
410 */
411 public final void trace(Object message) {
412
413 if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
414 log(SimpleLog.LOG_LEVEL_TRACE, message, null);
415 }
416 }
417
418 /**
419 * <p>
420 * Log an error with trace log level.
421 * </p>
422 */
423 public final void trace(Object message, Throwable t) {
424
425 if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
426 log(SimpleLog.LOG_LEVEL_TRACE, message, t);
427 }
428 }
429
430 /**
431 * <p>
432 * Log a message with info log level.
433 * </p>
434 */
435 public final void info(Object message) {
436
437 if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
438 log(SimpleLog.LOG_LEVEL_INFO, message, null);
439 }
440 }
441
442 /**
443 * <p>
444 * Log an error with info log level.
445 * </p>
446 */
447 public final void info(Object message, Throwable t) {
448
449 if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
450 log(SimpleLog.LOG_LEVEL_INFO, message, t);
451 }
452 }
453
454 /**
455 * <p>
456 * Log a message with warn log level.
457 * </p>
458 */
459 public final void warn(Object message) {
460
461 if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
462 log(SimpleLog.LOG_LEVEL_WARN, message, null);
463 }
464 }
465
466 /**
467 * <p>
468 * Log an error with warn log level.
469 * </p>
470 */
471 public final void warn(Object message, Throwable t) {
472
473 if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
474 log(SimpleLog.LOG_LEVEL_WARN, message, t);
475 }
476 }
477
478 /**
479 * <p>
480 * Log a message with error log level.
481 * </p>
482 */
483 public final void error(Object message) {
484
485 if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
486 log(SimpleLog.LOG_LEVEL_ERROR, message, null);
487 }
488 }
489
490 /**
491 * <p>
492 * Log an error with error log level.
493 * </p>
494 */
495 public final void error(Object message, Throwable t) {
496
497 if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
498 log(SimpleLog.LOG_LEVEL_ERROR, message, t);
499 }
500 }
501
502 /**
503 * <p>
504 * Log a message with fatal log level.
505 * </p>
506 */
507 public final void fatal(Object message) {
508
509 if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
510 log(SimpleLog.LOG_LEVEL_FATAL, message, null);
511 }
512 }
513
514 /**
515 * <p>
516 * Log an error with fatal log level.
517 * </p>
518 */
519 public final void fatal(Object message, Throwable t) {
520
521 if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
522 log(SimpleLog.LOG_LEVEL_FATAL, message, t);
523 }
524 }
525
526 /**
527 * <p>
528 * Are debug messages currently enabled?
529 * </p>
530 *
531 * <p>
532 * This allows expensive operations such as <code>String</code> concatenation
533 * to be avoided when the message will be ignored by the logger.
534 * </p>
535 */
536 public final boolean isDebugEnabled() {
537
538 return isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG);
539 }
540
541 /**
542 * <p>
543 * Are error messages currently enabled?
544 * </p>
545 *
546 * <p>
547 * This allows expensive operations such as <code>String</code> concatenation
548 * to be avoided when the message will be ignored by the logger.
549 * </p>
550 */
551 public final boolean isErrorEnabled() {
552
553 return isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR);
554 }
555
556 /**
557 * <p>
558 * Are fatal messages currently enabled?
559 * </p>
560 *
561 * <p>
562 * This allows expensive operations such as <code>String</code> concatenation
563 * to be avoided when the message will be ignored by the logger.
564 * </p>
565 */
566 public final boolean isFatalEnabled() {
567
568 return isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL);
569 }
570
571 /**
572 * <p>
573 * Are info messages currently enabled?
574 * </p>
575 *
576 * <p>
577 * This allows expensive operations such as <code>String</code> concatenation
578 * to be avoided when the message will be ignored by the logger.
579 * </p>
580 */
581 public final boolean isInfoEnabled() {
582
583 return isLevelEnabled(SimpleLog.LOG_LEVEL_INFO);
584 }
585
586 /**
587 * <p>
588 * Are trace messages currently enabled?
589 * </p>
590 *
591 * <p>
592 * This allows expensive operations such as <code>String</code> concatenation
593 * to be avoided when the message will be ignored by the logger.
594 * </p>
595 */
596 public final boolean isTraceEnabled() {
597
598 return isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE);
599 }
600
601 /**
602 * <p>
603 * Are warn messages currently enabled?
604 * </p>
605 *
606 * <p>
607 * This allows expensive operations such as <code>String</code> concatenation
608 * to be avoided when the message will be ignored by the logger.
609 * </p>
610 */
611 public final boolean isWarnEnabled() {
612
613 return isLevelEnabled(SimpleLog.LOG_LEVEL_WARN);
614 }
615
616 /**
617 * Return the thread context class loader if available. Otherwise return null.
618 *
619 * The thread context class loader is available for JDK 1.2 or later, if
620 * certain security conditions are met.
621 *
622 * @exception LogConfigurationException
623 * if a suitable class loader cannot be identified.
624 */
625 private static ClassLoader getContextClassLoader() {
626 ClassLoader classLoader = null;
627
628 if (classLoader == null) {
629 try {
630 // Are we running on a JDK 1.2 or later system?
631 Method method = Thread.class.getMethod("getContextClassLoader");
632
633 // Get the thread context class loader (if there is one)
634 try {
635 classLoader = (ClassLoader) method.invoke(Thread.currentThread());
636 } catch (IllegalAccessException e) {
637 ; // ignore
638 } catch (InvocationTargetException e) {
639 /**
640 * InvocationTargetException is thrown by 'invoke' when the method
641 * being invoked (getContextClassLoader) throws an exception.
642 *
643 * getContextClassLoader() throws SecurityException when the context
644 * class loader isn't an ancestor of the calling class's class loader,
645 * or if security permissions are restricted.
646 *
647 * In the first case (not related), we want to ignore and keep going.
648 * We cannot help but also ignore the second with the logic below, but
649 * other calls elsewhere (to obtain a class loader) will trigger this
650 * exception where we can make a distinction.
651 */
652 if (e.getTargetException() instanceof SecurityException) {
653 ; // ignore
654 } else {
655 // Capture 'e.getTargetException()' exception for details
656 // alternate: log 'e.getTargetException()', and pass back 'e'.
657 throw new LogConfigurationException("Unexpected InvocationTargetException", e.getTargetException());
658 }
659 }
660 } catch (NoSuchMethodException e) {
661 // Assume we are running on JDK 1.1
662 ; // ignore
663 }
664 }
665
666 if (classLoader == null) {
667 classLoader = SimpleLog.class.getClassLoader();
668 }
669
670 // Return the selected class loader
671 return classLoader;
672 }
673
674 private static InputStream getResourceAsStream(final String name) {
675 return AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
676 public InputStream run() {
677 ClassLoader threadCL = getContextClassLoader();
678
679 if (threadCL != null) {
680 return threadCL.getResourceAsStream(name);
681 } else {
682 return ClassLoader.getSystemResourceAsStream(name);
683 }
684 }
685 });
686 }
687 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.InputStream;
19 import java.io.Serializable;
20 import java.lang.reflect.InvocationTargetException;
21 import java.lang.reflect.Method;
22 import java.security.AccessController;
23 import java.security.PrivilegedAction;
24 import java.text.DateFormat;
25 import java.text.SimpleDateFormat;
26 import java.util.Date;
27 import java.util.Properties;
28
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogConfigurationException;
31
32 /**
33 * <p>
34 * Simple implementation of Log that sends all enabled log messages, for all
35 * defined loggers, to System.err. The following system properties are supported
36 * to configure the behavior of this logger:
37 * </p>
38 * <ul>
39 * <li><code>org.apache.commons.logging.simplelog.defaultlog</code> - Default
40 * logging detail level for all instances of SimpleLog. Must be one of ("trace",
41 * "debug", "info", "warn", "error", or "fatal"). If not specified, defaults to
42 * "info".</li>
43 * <li><code>org.apache.commons.logging.simplelog.log.xxxxx</code> - Logging
44 * detail level for a SimpleLog instance named "xxxxx". Must be one of ("trace",
45 * "debug", "info", "warn", "error", or "fatal"). If not specified, the default
46 * logging detail level is used.</li>
47 * <li><code>org.apache.commons.logging.simplelog.showlogname</code> - Set to
48 * <code>true</code> if you want the Log instance name to be included in output
49 * messages. Defaults to <code>false</code>.</li>
50 * <li><code>org.apache.commons.logging.simplelog.showShortLogname</code> - Set
51 * to <code>true</code> if you want the last component of the name to be
52 * included in output messages. Defaults to <code>true</code>.</li>
53 * <li><code>org.apache.commons.logging.simplelog.showdatetime</code> - Set to
54 * <code>true</code> if you want the current date and time to be included in
55 * output messages. Default is <code>false</code>.</li>
56 * <li><code>org.apache.commons.logging.simplelog.dateTimeFormat</code> - The
57 * date and time format to be used in the output messages. The pattern
58 * describing the date and time format is the same that is used in
59 * <code>java.text.SimpleDateFormat</code>. If the format is not specified or is
60 * invalid, the default format is used. The default format is
61 * <code>yyyy/MM/dd HH:mm:ss:SSS zzz</code>.</li>
62 * </ul>
63 *
64 * <p>
65 * In addition to looking for system properties with the names specified above,
66 * this implementation also checks for a class loader resource named
67 * <code>"simplelog.properties"</code>, and includes any matching definitions
68 * from this resource (if it exists).
69 * </p>
70 *
71 * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
72 * @author Rod Waldhoff
73 * @author Robert Burrell Donkin
74 *
75 * @version $Id: SimpleLog.java,v 1.21 2004/06/06 20:47:56 rdonkin Exp $
76 */
77 public class SimpleLog implements Log, Serializable {
78
79 private static final long serialVersionUID = 136942970684951178L;
80
81 // ------------------------------------------------------- Class Attributes
82
83 /** All system properties used by <code>SimpleLog</code> start with this */
84 static protected final String systemPrefix = "org.apache.commons.logging.simplelog.";
85
86 /** Properties loaded from simplelog.properties */
87 static protected final Properties simpleLogProps = new Properties();
88
89 /** The default format to use when formatting dates */
90 static protected final String DEFAULT_DATE_TIME_FORMAT = "yyyy/MM/dd HH:mm:ss:SSS zzz";
91
92 /** Include the instance name in the log message? */
93 static protected boolean showLogName = false;
94 /**
95 * Include the short name ( last component ) of the logger in the log message.
96 * Defaults to true - otherwise we'll be lost in a flood of messages without
97 * knowing who sends them.
98 */
99 static protected boolean showShortName = true;
100 /** Include the current time in the log message */
101 static protected boolean showDateTime = false;
102 /** The date and time format to use in the log message */
103 static protected String dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
104 /** Used to format times */
105 static protected DateFormat dateFormatter = null;
106
107 // ---------------------------------------------------- Log Level Constants
108
109 /** "Trace" level logging. */
110 public static final int LOG_LEVEL_TRACE = 1;
111 /** "Debug" level logging. */
112 public static final int LOG_LEVEL_DEBUG = 2;
113 /** "Info" level logging. */
114 public static final int LOG_LEVEL_INFO = 3;
115 /** "Warn" level logging. */
116 public static final int LOG_LEVEL_WARN = 4;
117 /** "Error" level logging. */
118 public static final int LOG_LEVEL_ERROR = 5;
119 /** "Fatal" level logging. */
120 public static final int LOG_LEVEL_FATAL = 6;
121
122 /** Enable all logging levels */
123 public static final int LOG_LEVEL_ALL = (LOG_LEVEL_TRACE - 1);
124
125 /** Enable no logging levels */
126 public static final int LOG_LEVEL_OFF = (LOG_LEVEL_FATAL + 1);
127
128 // ------------------------------------------------------------ Initializer
129
130 private static String getStringProperty(String name) {
131 String prop = null;
132 try {
133 prop = System.getProperty(name);
134 } catch (SecurityException e) {
135 ; // Ignore
136 }
137 return (prop == null) ? simpleLogProps.getProperty(name) : prop;
138 }
139
140 private static String getStringProperty(String name, String dephault) {
141 String prop = getStringProperty(name);
142 return (prop == null) ? dephault : prop;
143 }
144
145 private static boolean getBooleanProperty(String name, boolean dephault) {
146 String prop = getStringProperty(name);
147 return (prop == null) ? dephault : "true".equalsIgnoreCase(prop);
148 }
149
150 // Initialize class attributes.
151 // Load properties file, if found.
152 // Override with system properties.
153 static {
154 // Add props from the resource simplelog.properties
155 InputStream in = getResourceAsStream("simplelog.properties");
156 if (null != in) {
157 try {
158 simpleLogProps.load(in);
159 } catch (java.io.IOException e) {
160 // ignored
161 } finally {
162 try {
163 in.close();
164 } catch (java.io.IOException e) {
165 // ignored
166 }
167 }
168 }
169
170 showLogName = getBooleanProperty(systemPrefix + "showlogname", showLogName);
171 showShortName = getBooleanProperty(systemPrefix + "showShortLogname", showShortName);
172 showDateTime = getBooleanProperty(systemPrefix + "showdatetime", showDateTime);
173
174 if (showDateTime) {
175 dateTimeFormat = getStringProperty(systemPrefix + "dateTimeFormat", dateTimeFormat);
176 try {
177 dateFormatter = new SimpleDateFormat(dateTimeFormat);
178 } catch (IllegalArgumentException e) {
179 // If the format pattern is invalid - use the default format
180 dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
181 dateFormatter = new SimpleDateFormat(dateTimeFormat);
182 }
183 }
184 }
185
186 // ------------------------------------------------------------- Attributes
187
188 /** The name of this simple log instance */
189 protected String logName = null;
190 /** The current log level */
191 protected int currentLogLevel;
192 /** The short name of this simple log instance */
193 private String shortLogName = null;
194
195 // ------------------------------------------------------------ Constructor
196
197 /**
198 * Construct a simple log with given name.
199 *
200 * @param name
201 * log name
202 */
203 public SimpleLog(String name) {
204
205 logName = name;
206
207 // Set initial log level
208 // Used to be: set default log level to ERROR
209 // IMHO it should be lower, but at least info ( costin ).
210 setLevel(SimpleLog.LOG_LEVEL_INFO);
211
212 // Set log level from properties
213 String lvl = getStringProperty(systemPrefix + "log." + logName);
214 int i = String.valueOf(name).lastIndexOf(".");
215 while (null == lvl && i > -1) {
216 name = name.substring(0, i);
217 lvl = getStringProperty(systemPrefix + "log." + name);
218 i = String.valueOf(name).lastIndexOf(".");
219 }
220
221 if (null == lvl) {
222 lvl = getStringProperty(systemPrefix + "defaultlog");
223 }
224
225 if ("all".equalsIgnoreCase(lvl)) {
226 setLevel(SimpleLog.LOG_LEVEL_ALL);
227 } else if ("trace".equalsIgnoreCase(lvl)) {
228 setLevel(SimpleLog.LOG_LEVEL_TRACE);
229 } else if ("debug".equalsIgnoreCase(lvl)) {
230 setLevel(SimpleLog.LOG_LEVEL_DEBUG);
231 } else if ("info".equalsIgnoreCase(lvl)) {
232 setLevel(SimpleLog.LOG_LEVEL_INFO);
233 } else if ("warn".equalsIgnoreCase(lvl)) {
234 setLevel(SimpleLog.LOG_LEVEL_WARN);
235 } else if ("error".equalsIgnoreCase(lvl)) {
236 setLevel(SimpleLog.LOG_LEVEL_ERROR);
237 } else if ("fatal".equalsIgnoreCase(lvl)) {
238 setLevel(SimpleLog.LOG_LEVEL_FATAL);
239 } else if ("off".equalsIgnoreCase(lvl)) {
240 setLevel(SimpleLog.LOG_LEVEL_OFF);
241 }
242
243 }
244
245 // -------------------------------------------------------- Properties
246
247 /**
248 * <p>
249 * Set logging level.
250 * </p>
251 *
252 * @param currentLogLevel
253 * new logging level
254 */
255 public void setLevel(int currentLogLevel) {
256
257 this.currentLogLevel = currentLogLevel;
258
259 }
260
261 /**
262 * <p>
263 * Get logging level.
264 * </p>
265 */
266 public int getLevel() {
267
268 return currentLogLevel;
269 }
270
271 // -------------------------------------------------------- Logging Methods
272
273 /**
274 * <p>
275 * Do the actual logging. This method assembles the message and then calls
276 * <code>write()</code> to cause it to be written.
277 * </p>
278 *
279 * @param type
280 * One of the LOG_LEVEL_XXX constants defining the log level
281 * @param message
282 * The message itself (typically a String)
283 * @param t
284 * The exception whose stack trace should be logged
285 */
286 protected void log(int type, Object message, Throwable t) {
287 // Use a string buffer for better performance
288 StringBuffer buf = new StringBuffer();
289
290 // Append date-time if so configured
291 if (showDateTime) {
292 buf.append(dateFormatter.format(new Date()));
293 buf.append(" ");
294 }
295
296 // Append a readable representation of the log level
297 switch (type) {
298 case SimpleLog.LOG_LEVEL_TRACE:
299 buf.append("[TRACE] ");
300 break;
301 case SimpleLog.LOG_LEVEL_DEBUG:
302 buf.append("[DEBUG] ");
303 break;
304 case SimpleLog.LOG_LEVEL_INFO:
305 buf.append("[INFO] ");
306 break;
307 case SimpleLog.LOG_LEVEL_WARN:
308 buf.append("[WARN] ");
309 break;
310 case SimpleLog.LOG_LEVEL_ERROR:
311 buf.append("[ERROR] ");
312 break;
313 case SimpleLog.LOG_LEVEL_FATAL:
314 buf.append("[FATAL] ");
315 break;
316 }
317
318 // Append the name of the log instance if so configured
319 if (showShortName) {
320 if (shortLogName == null) {
321 // Cut all but the last component of the name for both styles
322 shortLogName = logName.substring(logName.lastIndexOf(".") + 1);
323 shortLogName = shortLogName.substring(shortLogName.lastIndexOf("/") + 1);
324 }
325 buf.append(String.valueOf(shortLogName)).append(" - ");
326 } else if (showLogName) {
327 buf.append(String.valueOf(logName)).append(" - ");
328 }
329
330 // Append the message
331 buf.append(String.valueOf(message));
332
333 // Append stack trace if not null
334 if (t != null) {
335 buf.append(" <");
336 buf.append(t.toString());
337 buf.append(">");
338
339 java.io.StringWriter sw = new java.io.StringWriter(1024);
340 java.io.PrintWriter pw = new java.io.PrintWriter(sw);
341 t.printStackTrace(pw);
342 pw.close();
343 buf.append(sw.toString());
344 }
345
346 // Print to the appropriate destination
347 write(buf);
348
349 }
350
351 /**
352 * <p>
353 * Write the content of the message accumulated in the specified
354 * <code>StringBuffer</code> to the appropriate output destination. The
355 * default implementation writes to <code>System.err</code>.
356 * </p>
357 *
358 * @param buffer
359 * A <code>StringBuffer</code> containing the accumulated text to be
360 * logged
361 */
362 protected void write(StringBuffer buffer) {
363
364 System.err.println(buffer.toString());
365
366 }
367
368 /**
369 * Is the given log level currently enabled?
370 *
371 * @param logLevel
372 * is this level enabled?
373 */
374 protected boolean isLevelEnabled(int logLevel) {
375 // log level are numerically ordered so can use simple numeric
376 // comparison
377 return (logLevel >= currentLogLevel);
378 }
379
380 // -------------------------------------------------------- Log Implementation
381
382 /**
383 * <p>
384 * Log a message with debug log level.
385 * </p>
386 */
387 public final void debug(Object message) {
388
389 if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
390 log(SimpleLog.LOG_LEVEL_DEBUG, message, null);
391 }
392 }
393
394 /**
395 * <p>
396 * Log an error with debug log level.
397 * </p>
398 */
399 public final void debug(Object message, Throwable t) {
400
401 if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
402 log(SimpleLog.LOG_LEVEL_DEBUG, message, t);
403 }
404 }
405
406 /**
407 * <p>
408 * Log a message with trace log level.
409 * </p>
410 */
411 public final void trace(Object message) {
412
413 if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
414 log(SimpleLog.LOG_LEVEL_TRACE, message, null);
415 }
416 }
417
418 /**
419 * <p>
420 * Log an error with trace log level.
421 * </p>
422 */
423 public final void trace(Object message, Throwable t) {
424
425 if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
426 log(SimpleLog.LOG_LEVEL_TRACE, message, t);
427 }
428 }
429
430 /**
431 * <p>
432 * Log a message with info log level.
433 * </p>
434 */
435 public final void info(Object message) {
436
437 if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
438 log(SimpleLog.LOG_LEVEL_INFO, message, null);
439 }
440 }
441
442 /**
443 * <p>
444 * Log an error with info log level.
445 * </p>
446 */
447 public final void info(Object message, Throwable t) {
448
449 if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
450 log(SimpleLog.LOG_LEVEL_INFO, message, t);
451 }
452 }
453
454 /**
455 * <p>
456 * Log a message with warn log level.
457 * </p>
458 */
459 public final void warn(Object message) {
460
461 if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
462 log(SimpleLog.LOG_LEVEL_WARN, message, null);
463 }
464 }
465
466 /**
467 * <p>
468 * Log an error with warn log level.
469 * </p>
470 */
471 public final void warn(Object message, Throwable t) {
472
473 if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
474 log(SimpleLog.LOG_LEVEL_WARN, message, t);
475 }
476 }
477
478 /**
479 * <p>
480 * Log a message with error log level.
481 * </p>
482 */
483 public final void error(Object message) {
484
485 if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
486 log(SimpleLog.LOG_LEVEL_ERROR, message, null);
487 }
488 }
489
490 /**
491 * <p>
492 * Log an error with error log level.
493 * </p>
494 */
495 public final void error(Object message, Throwable t) {
496
497 if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
498 log(SimpleLog.LOG_LEVEL_ERROR, message, t);
499 }
500 }
501
502 /**
503 * <p>
504 * Log a message with fatal log level.
505 * </p>
506 */
507 public final void fatal(Object message) {
508
509 if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
510 log(SimpleLog.LOG_LEVEL_FATAL, message, null);
511 }
512 }
513
514 /**
515 * <p>
516 * Log an error with fatal log level.
517 * </p>
518 */
519 public final void fatal(Object message, Throwable t) {
520
521 if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
522 log(SimpleLog.LOG_LEVEL_FATAL, message, t);
523 }
524 }
525
526 /**
527 * <p>
528 * Are debug messages currently enabled?
529 * </p>
530 *
531 * <p>
532 * This allows expensive operations such as <code>String</code> concatenation
533 * to be avoided when the message will be ignored by the logger.
534 * </p>
535 */
536 public final boolean isDebugEnabled() {
537
538 return isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG);
539 }
540
541 /**
542 * <p>
543 * Are error messages currently enabled?
544 * </p>
545 *
546 * <p>
547 * This allows expensive operations such as <code>String</code> concatenation
548 * to be avoided when the message will be ignored by the logger.
549 * </p>
550 */
551 public final boolean isErrorEnabled() {
552
553 return isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR);
554 }
555
556 /**
557 * <p>
558 * Are fatal messages currently enabled?
559 * </p>
560 *
561 * <p>
562 * This allows expensive operations such as <code>String</code> concatenation
563 * to be avoided when the message will be ignored by the logger.
564 * </p>
565 */
566 public final boolean isFatalEnabled() {
567
568 return isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL);
569 }
570
571 /**
572 * <p>
573 * Are info messages currently enabled?
574 * </p>
575 *
576 * <p>
577 * This allows expensive operations such as <code>String</code> concatenation
578 * to be avoided when the message will be ignored by the logger.
579 * </p>
580 */
581 public final boolean isInfoEnabled() {
582
583 return isLevelEnabled(SimpleLog.LOG_LEVEL_INFO);
584 }
585
586 /**
587 * <p>
588 * Are trace messages currently enabled?
589 * </p>
590 *
591 * <p>
592 * This allows expensive operations such as <code>String</code> concatenation
593 * to be avoided when the message will be ignored by the logger.
594 * </p>
595 */
596 public final boolean isTraceEnabled() {
597
598 return isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE);
599 }
600
601 /**
602 * <p>
603 * Are warn messages currently enabled?
604 * </p>
605 *
606 * <p>
607 * This allows expensive operations such as <code>String</code> concatenation
608 * to be avoided when the message will be ignored by the logger.
609 * </p>
610 */
611 public final boolean isWarnEnabled() {
612
613 return isLevelEnabled(SimpleLog.LOG_LEVEL_WARN);
614 }
615
616 /**
617 * Return the thread context class loader if available. Otherwise return null.
618 *
619 * The thread context class loader is available for JDK 1.2 or later, if
620 * certain security conditions are met.
621 *
622 * @exception LogConfigurationException
623 * if a suitable class loader cannot be identified.
624 */
625 private static ClassLoader getContextClassLoader() {
626 ClassLoader classLoader = null;
627
628 if (classLoader == null) {
629 try {
630 // Are we running on a JDK 1.2 or later system?
631 Method method = Thread.class.getMethod("getContextClassLoader");
632
633 // Get the thread context class loader (if there is one)
634 try {
635 classLoader = (ClassLoader) method.invoke(Thread.currentThread());
636 } catch (IllegalAccessException e) {
637 ; // ignore
638 } catch (InvocationTargetException e) {
639 /**
640 * InvocationTargetException is thrown by 'invoke' when the method
641 * being invoked (getContextClassLoader) throws an exception.
642 *
643 * getContextClassLoader() throws SecurityException when the context
644 * class loader isn't an ancestor of the calling class's class loader,
645 * or if security permissions are restricted.
646 *
647 * In the first case (not related), we want to ignore and keep going.
648 * We cannot help but also ignore the second with the logic below, but
649 * other calls elsewhere (to obtain a class loader) will trigger this
650 * exception where we can make a distinction.
651 */
652 if (e.getTargetException() instanceof SecurityException) {
653 ; // ignore
654 } else {
655 // Capture 'e.getTargetException()' exception for details
656 // alternate: log 'e.getTargetException()', and pass back 'e'.
657 throw new LogConfigurationException("Unexpected InvocationTargetException", e.getTargetException());
658 }
659 }
660 } catch (NoSuchMethodException e) {
661 // Assume we are running on JDK 1.1
662 ; // ignore
663 }
664 }
665
666 if (classLoader == null) {
667 classLoader = SimpleLog.class.getClassLoader();
668 }
669
670 // Return the selected class loader
671 return classLoader;
672 }
673
674 private static InputStream getResourceAsStream(final String name) {
675 return AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
676 public InputStream run() {
677 ClassLoader threadCL = getContextClassLoader();
678
679 if (threadCL != null) {
680 return threadCL.getResourceAsStream(name);
681 } else {
682 return ClassLoader.getSystemResourceAsStream(name);
683 }
684 }
685 });
686 }
687 }
0 <body>
1
2 <p>SLF4J based implementation of commons-logging wrapper APIs.</p>
3
4 </body>
0 <body>
1
2 <p>SLF4J based implementation of commons-logging wrapper APIs.</p>
3
4 </body>
0 <!--
1
2 Copyright 2001-2004 The Apache Software Foundation.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15
16 -->
17
18 <body>
19 <p>Jakarta Commons Logging implemented over SLF4J.</p>
20
21
22 <h3>Overview</h3>
23
24 <p>This package contains the same public user interface as <a
25 href="http://jakarta.apache.org/commons/logging/">Jakarta Commons
26 Logging (JCL)</a>. It is intended as a 100% compatible drop-in
27 replacement for the original JCL version 1.0.4.
28 </p>
29
30 <p>As the original JCL version 1.0.4, the present version supports
31 various logging APIs. It differs from the original in implementation
32 but not the public API. This implementation uses SLF4J under the
33 covers. As as such, all the logging systems that SLF4J supports,
34 e.g. NOP, Simple, JDK14, nlog4j are supported by this version of JCL.
35 </p>
36
37 <h3>Quick Start Guide</h3>
38
39 <p>For those impatient to just get on with it, the following example
40 illustrates the typical declaration and use of a logger that is named (by
41 convention) after the calling class:
42
43 <pre>
44 import org.apache.commons.logging.Log;
45 import org.apache.commons.logging.LogFactory;
46
47 public class Foo {
48
49 static Log log = LogFactory.getLog(Foo.class);
50
51 public void foo() {
52 ...
53 try {
54 if (log.isDebugEnabled()) {
55 log.debug("About to do something to object " + name);
56 }
57 name.bar();
58 } catch (IllegalStateException e) {
59 log.error("Something bad happened to " + name, e);
60 }
61 ...
62 }
63 </pre>
64
65 <h3>Configuring the Commons Logging Package</h3>
66
67 <p>In this version of JCL, the selection of the logging system to use
68 is chosen by the underlying SLF4J API. Consequently, all JCL-specific
69 configuration parameters are ignored.
70 </p>
71
72 <h4>Choosing a <code>LogFactory</code> Implementation</h4>
73
74 <p>From an application perspective, the first requirement is to
75 retrieve an object reference to the <code>LogFactory</code> instance
76 that will be used to create <code><a href="Log.html">Log</a></code>
77 instances for this application. This is normally accomplished by
78 calling the static <code>getFactory()</code> method. This method
79 always returns the same factory, i.e. a unique instance of the <a
80 href="impl/SLF4FLogFactory.html">SLF4FLogFactory</a> class.
81 </p>
82
83
84
85 <h4>Configuring the Underlying Logging System</h4>
86
87 <p>The basic principle is that the user is totally responsible for the
88 configuration of the underlying logging system.
89 Commons-logging should not change the existing configuration.</p>
90
91 <p>Each individual <a href="Log.html">Log</a> implementation may
92 support its own configuration properties. These will be documented in the
93 class descriptions for the corresponding implementation class.</p>
94
95 <p>Finally, some <code>Log</code> implementations (such as the one for Log4J)
96 require an external configuration file for the entire logging environment.
97 This file should be prepared in a manner that is specific to the actual logging
98 technology being used.</p>
99
100
101 <h3>Using the Logging Package APIs</h3>
102
103 <p>Use of the Logging Package APIs, from the perspective of an application
104 component, consists of the following steps:</p>
105 <ol>
106 <li>Acquire a reference to an instance of
107 <a href="Log.html">org.apache.commons.logging.Log</a>, by calling the
108 factory method
109 <a href="LogFactory.html#getInstance(java.lang.String)">
110 LogFactory.getInstance(String name)</a>. Your application can contain
111 references to multiple loggers that are used for different
112 purposes. A typical scenario for a server application is to have each
113 major component of the server use its own Log instance.</li>
114 <li>Cause messages to be logged (if the corresponding detail level is enabled)
115 by calling appropriate methods (<code>trace()</code>, <code>debug()</code>,
116 <code>info()</code>, <code>warn()</code>, <code>error</code>, and
117 <code>fatal()</code>).</li>
118 </ol>
119
120 <p>For convenience, <code>LogFactory</code> also offers a static method
121 <code>getLog()</code> that combines the typical two-step pattern:</p>
122 <pre>
123 Log log = LogFactory.getFactory().getInstance(Foo.class);
124 </pre>
125 <p>into a single method call:</p>
126 <pre>
127 Log log = LogFactory.getLog(Foo.class);
128 </pre>
129
130 <p>For example, you might use the following technique to initialize and
131 use a <a href="Log.html">Log</a> instance in an application component:</p>
132 <pre>
133 import org.apache.commons.logging.Log;
134 import org.apache.commons.logging.LogFactory;
135
136 public class MyComponent {
137
138 protected static Log log =
139 LogFactory.getLog(MyComponent.class);
140
141 // Called once at startup time
142 public void start() {
143 ...
144 log.info("MyComponent started");
145 ...
146 }
147
148 // Called once at shutdown time
149 public void stop() {
150 ...
151 log.info("MyComponent stopped");
152 ...
153 }
154
155 // Called repeatedly to process a particular argument value
156 // which you want logged if debugging is enabled
157 public void process(String value) {
158 ...
159 // Do the string concatenation only if logging is enabled
160 if (log.isDebugEnabled())
161 log.debug("MyComponent processing " + value);
162 ...
163 }
164
165 }
166 </pre>
167
168 </body>
0 <!--
1
2 Copyright 2001-2004 The Apache Software Foundation.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15
16 -->
17
18 <body>
19 <p>Jakarta Commons Logging implemented over SLF4J.</p>
20
21
22 <h3>Overview</h3>
23
24 <p>This package contains the same public user interface as <a
25 href="http://jakarta.apache.org/commons/logging/">Jakarta Commons
26 Logging (JCL)</a>. It is intended as a 100% compatible drop-in
27 replacement for the original JCL version 1.0.4.
28 </p>
29
30 <p>As the original JCL version 1.0.4, the present version supports
31 various logging APIs. It differs from the original in implementation
32 but not the public API. This implementation uses SLF4J under the
33 covers. As as such, all the logging systems that SLF4J supports,
34 e.g. NOP, Simple, JDK14, nlog4j are supported by this version of JCL.
35 </p>
36
37 <h3>Quick Start Guide</h3>
38
39 <p>For those impatient to just get on with it, the following example
40 illustrates the typical declaration and use of a logger that is named (by
41 convention) after the calling class:
42
43 <pre>
44 import org.apache.commons.logging.Log;
45 import org.apache.commons.logging.LogFactory;
46
47 public class Foo {
48
49 static Log log = LogFactory.getLog(Foo.class);
50
51 public void foo() {
52 ...
53 try {
54 if (log.isDebugEnabled()) {
55 log.debug("About to do something to object " + name);
56 }
57 name.bar();
58 } catch (IllegalStateException e) {
59 log.error("Something bad happened to " + name, e);
60 }
61 ...
62 }
63 </pre>
64
65 <h3>Configuring the Commons Logging Package</h3>
66
67 <p>In this version of JCL, the selection of the logging system to use
68 is chosen by the underlying SLF4J API. Consequently, all JCL-specific
69 configuration parameters are ignored.
70 </p>
71
72 <h4>Choosing a <code>LogFactory</code> Implementation</h4>
73
74 <p>From an application perspective, the first requirement is to
75 retrieve an object reference to the <code>LogFactory</code> instance
76 that will be used to create <code><a href="Log.html">Log</a></code>
77 instances for this application. This is normally accomplished by
78 calling the static <code>getFactory()</code> method. This method
79 always returns the same factory, i.e. a unique instance of the <a
80 href="impl/SLF4FLogFactory.html">SLF4FLogFactory</a> class.
81 </p>
82
83
84
85 <h4>Configuring the Underlying Logging System</h4>
86
87 <p>The basic principle is that the user is totally responsible for the
88 configuration of the underlying logging system.
89 Commons-logging should not change the existing configuration.</p>
90
91 <p>Each individual <a href="Log.html">Log</a> implementation may
92 support its own configuration properties. These will be documented in the
93 class descriptions for the corresponding implementation class.</p>
94
95 <p>Finally, some <code>Log</code> implementations (such as the one for Log4J)
96 require an external configuration file for the entire logging environment.
97 This file should be prepared in a manner that is specific to the actual logging
98 technology being used.</p>
99
100
101 <h3>Using the Logging Package APIs</h3>
102
103 <p>Use of the Logging Package APIs, from the perspective of an application
104 component, consists of the following steps:</p>
105 <ol>
106 <li>Acquire a reference to an instance of
107 <a href="Log.html">org.apache.commons.logging.Log</a>, by calling the
108 factory method
109 <a href="LogFactory.html#getInstance(java.lang.String)">
110 LogFactory.getInstance(String name)</a>. Your application can contain
111 references to multiple loggers that are used for different
112 purposes. A typical scenario for a server application is to have each
113 major component of the server use its own Log instance.</li>
114 <li>Cause messages to be logged (if the corresponding detail level is enabled)
115 by calling appropriate methods (<code>trace()</code>, <code>debug()</code>,
116 <code>info()</code>, <code>warn()</code>, <code>error</code>, and
117 <code>fatal()</code>).</li>
118 </ol>
119
120 <p>For convenience, <code>LogFactory</code> also offers a static method
121 <code>getLog()</code> that combines the typical two-step pattern:</p>
122 <pre>
123 Log log = LogFactory.getFactory().getInstance(Foo.class);
124 </pre>
125 <p>into a single method call:</p>
126 <pre>
127 Log log = LogFactory.getLog(Foo.class);
128 </pre>
129
130 <p>For example, you might use the following technique to initialize and
131 use a <a href="Log.html">Log</a> instance in an application component:</p>
132 <pre>
133 import org.apache.commons.logging.Log;
134 import org.apache.commons.logging.LogFactory;
135
136 public class MyComponent {
137
138 protected static Log log =
139 LogFactory.getLog(MyComponent.class);
140
141 // Called once at startup time
142 public void start() {
143 ...
144 log.info("MyComponent started");
145 ...
146 }
147
148 // Called once at shutdown time
149 public void stop() {
150 ...
151 log.info("MyComponent stopped");
152 ...
153 }
154
155 // Called repeatedly to process a particular argument value
156 // which you want logged if debugging is enabled
157 public void process(String value) {
158 ...
159 // Do the string concatenation only if logging is enabled
160 if (log.isDebugEnabled())
161 log.debug("MyComponent processing " + value);
162 ...
163 }
164
165 }
166 </pre>
167
168 </body>
0 Implementation-Title: jcl-over-slf4j
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: jcl.over.slf4j
3 Bundle-Name: jcl-over-slf4j
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.apache.commons.logging;version=1.2,
7 org.apache.commons.logging.impl;version=1.2
8 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}
0 Implementation-Title: jcl-over-slf4j
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: jcl.over.slf4j
3 Bundle-Name: jcl-over-slf4j
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.apache.commons.logging;version=1.2,
7 org.apache.commons.logging.impl;version=1.2
8 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}
0 org.apache.commons.logging.impl.SLF4JLogFactory
1
2 # Axis gets at JCL through its own mechanism as defined by Commons Discovery, which
3 # in turn follows the instructions found at:
4 # http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service Provider
0 org.apache.commons.logging.impl.SLF4JLogFactory
1
2 # Axis gets at JCL through its own mechanism as defined by Commons Discovery, which
3 # in turn follows the instructions found at:
4 # http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service Provider
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.apache.commons.logging;
26
27 import static org.junit.Assert.assertFalse;
28 import static org.junit.Assert.assertTrue;
29
30 import org.junit.Test;
31
32 public class InvokeJCLTest {
33
34 @Test
35 public void testIsEnabledAPI() {
36 // assume that we are running over slf4j-jdk14
37 Log log = LogFactory.getLog(InvokeJCLTest.class);
38 assertFalse(log.isTraceEnabled());
39 assertFalse(log.isDebugEnabled());
40 assertTrue(log.isInfoEnabled());
41 assertTrue(log.isWarnEnabled());
42 assertTrue(log.isErrorEnabled());
43 assertTrue(log.isFatalEnabled());
44 }
45
46 @Test
47 public void testPrintAPI() {
48 Log log = LogFactory.getLog(InvokeJCLTest.class);
49 Exception e = new Exception("just testing");
50
51 log.trace(null);
52 log.trace("trace message");
53
54 log.debug(null);
55 log.debug("debug message");
56
57 log.info(null);
58 log.info("info message");
59
60 log.warn(null);
61 log.warn("warn message");
62
63 log.error(null);
64 log.error("error message");
65
66 log.fatal(null);
67 log.fatal("fatal message");
68
69 log.trace(null, e);
70 log.trace("trace message", e);
71
72 log.debug(null, e);
73 log.debug("debug message", e);
74
75 log.info(null, e);
76 log.info("info message", e);
77
78 log.warn(null, e);
79 log.warn("warn message", e);
80
81 log.error(null, e);
82 log.error("error message", e);
83
84 log.fatal(null, e);
85 log.fatal("fatal message", e);
86 }
87 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.apache.commons.logging;
26
27 import static org.junit.Assert.assertFalse;
28 import static org.junit.Assert.assertTrue;
29
30 import org.junit.Test;
31
32 public class InvokeJCLTest {
33
34 @Test
35 public void testIsEnabledAPI() {
36 // assume that we are running over slf4j-jdk14
37 Log log = LogFactory.getLog(InvokeJCLTest.class);
38 assertFalse(log.isTraceEnabled());
39 assertFalse(log.isDebugEnabled());
40 assertTrue(log.isInfoEnabled());
41 assertTrue(log.isWarnEnabled());
42 assertTrue(log.isErrorEnabled());
43 assertTrue(log.isFatalEnabled());
44 }
45
46 @Test
47 public void testPrintAPI() {
48 Log log = LogFactory.getLog(InvokeJCLTest.class);
49 Exception e = new Exception("just testing");
50
51 log.trace(null);
52 log.trace("trace message");
53
54 log.debug(null);
55 log.debug("debug message");
56
57 log.info(null);
58 log.info("info message");
59
60 log.warn(null);
61 log.warn("warn message");
62
63 log.error(null);
64 log.error("error message");
65
66 log.fatal(null);
67 log.fatal("fatal message");
68
69 log.trace(null, e);
70 log.trace("trace message", e);
71
72 log.debug(null, e);
73 log.debug("debug message", e);
74
75 log.info(null, e);
76 log.info("info message", e);
77
78 log.warn(null, e);
79 log.warn("warn message", e);
80
81 log.error(null, e);
82 log.error("error message", e);
83
84 log.fatal(null, e);
85 log.fatal("fatal message", e);
86 }
87 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.apache.commons.logging.impl;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.ByteArrayOutputStream;
28 import java.io.IOException;
29 import java.io.ObjectInputStream;
30 import java.io.ObjectOutputStream;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.slf4j.impl.JDK14LoggerFactory;
38 import org.slf4j.spi.LocationAwareLogger;
39
40 public class SerializationTest {
41
42 ObjectInputStream ois;
43 ByteArrayOutputStream baos = new ByteArrayOutputStream();
44 ObjectOutputStream oos;
45
46 @Before
47 public void setUp() throws Exception {
48 oos = new ObjectOutputStream(baos);
49 }
50
51 @After
52 public void tearDown() throws Exception {
53 oos.close();
54 }
55
56 public void verify() throws IOException, ClassNotFoundException {
57 ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
58 ois = new ObjectInputStream(bis);
59
60 Log resuscitatedLog = (Log) ois.readObject();
61 // tests that the "private transient Logger logger" field is non-null
62 resuscitatedLog.debug("");
63 resuscitatedLog.isDebugEnabled();
64 }
65
66 @Test
67 public void testSLF4JLog() throws Exception {
68 JDK14LoggerFactory factory = new JDK14LoggerFactory();
69 SLF4JLog log = new SLF4JLog(factory.getLogger("x"));
70 oos.writeObject(log);
71 verify();
72 }
73
74 @Test
75 public void testSmoke() throws Exception {
76 Log log = LogFactory.getLog("testing");
77 oos.writeObject(log);
78 verify();
79 }
80
81 @Test
82 public void testLocationAware() throws Exception {
83 JDK14LoggerFactory factory = new JDK14LoggerFactory();
84 SLF4JLocationAwareLog log = new SLF4JLocationAwareLog((LocationAwareLogger) factory.getLogger("x"));
85 oos.writeObject(log);
86 verify();
87 }
88 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.apache.commons.logging.impl;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.ByteArrayOutputStream;
28 import java.io.IOException;
29 import java.io.ObjectInputStream;
30 import java.io.ObjectOutputStream;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.slf4j.impl.JDK14LoggerFactory;
38 import org.slf4j.spi.LocationAwareLogger;
39
40 public class SerializationTest {
41
42 ObjectInputStream ois;
43 ByteArrayOutputStream baos = new ByteArrayOutputStream();
44 ObjectOutputStream oos;
45
46 @Before
47 public void setUp() throws Exception {
48 oos = new ObjectOutputStream(baos);
49 }
50
51 @After
52 public void tearDown() throws Exception {
53 oos.close();
54 }
55
56 public void verify() throws IOException, ClassNotFoundException {
57 ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
58 ois = new ObjectInputStream(bis);
59
60 Log resuscitatedLog = (Log) ois.readObject();
61 // tests that the "private transient Logger logger" field is non-null
62 resuscitatedLog.debug("");
63 resuscitatedLog.isDebugEnabled();
64 }
65
66 @Test
67 public void testSLF4JLog() throws Exception {
68 JDK14LoggerFactory factory = new JDK14LoggerFactory();
69 SLF4JLog log = new SLF4JLog(factory.getLogger("x"));
70 oos.writeObject(log);
71 verify();
72 }
73
74 @Test
75 public void testSmoke() throws Exception {
76 Log log = LogFactory.getLog("testing");
77 oos.writeObject(log);
78 verify();
79 }
80
81 @Test
82 public void testLocationAware() throws Exception {
83 JDK14LoggerFactory factory = new JDK14LoggerFactory();
84 SLF4JLocationAwareLog log = new SLF4JLocationAwareLog((LocationAwareLogger) factory.getLogger("x"));
85 oos.writeObject(log);
86 verify();
87 }
88 }
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>jul-to-slf4j</artifactId>
13
14 <packaging>jar</packaging>
15 <name>JUL to SLF4J bridge</name>
16 <description>JUL to SLF4J bridge</description>
17
18 <url>http://www.slf4j.org</url>
19
20 <dependencies>
21 <dependency>
22 <groupId>org.slf4j</groupId>
23 <artifactId>slf4j-api</artifactId>
24 </dependency>
25 <dependency>
26 <groupId>org.slf4j</groupId>
27 <artifactId>slf4j-log4j12</artifactId>
28 <version>${project.version}</version>
29 <scope>test</scope>
30 </dependency>
31 </dependencies>
32
33 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>jul-to-slf4j</artifactId>
13
14 <packaging>jar</packaging>
15 <name>JUL to SLF4J bridge</name>
16 <description>JUL to SLF4J bridge</description>
17
18 <url>http://www.slf4j.org</url>
19
20 <dependencies>
21 <dependency>
22 <groupId>org.slf4j</groupId>
23 <artifactId>slf4j-api</artifactId>
24 </dependency>
25 <dependency>
26 <groupId>org.slf4j</groupId>
27 <artifactId>slf4j-log4j12</artifactId>
28 <version>${project.version}</version>
29 <scope>test</scope>
30 </dependency>
31 </dependencies>
32
33 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import java.text.MessageFormat;
27 import java.util.MissingResourceException;
28 import java.util.ResourceBundle;
29 import java.util.logging.Handler;
30 import java.util.logging.Level;
31 import java.util.logging.LogManager;
32 import java.util.logging.LogRecord;
33
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.slf4j.spi.LocationAwareLogger;
37
38 // Based on http://jira.qos.ch/browse/SLF4J-30
39
40 /**
41 * <p>Bridge/route all JUL log records to the SLF4J API.</p>
42 * <p>Essentially, the idea is to install on the root logger an instance of
43 * <code>SLF4JBridgeHandler</code> as the sole JUL handler in the system. Subsequently, the
44 * SLF4JBridgeHandler instance will redirect all JUL log records are redirected
45 * to the SLF4J API based on the following mapping of levels:
46 * </p>
47 * <pre>
48 * FINEST -&gt; TRACE
49 * FINER -&gt; DEBUG
50 * FINE -&gt; DEBUG
51 * INFO -&gt; INFO
52 * WARNING -&gt; WARN
53 * SEVERE -&gt; ERROR</pre>
54 * <p><b>Programmatic installation:</b></p>
55 * <pre>
56 * // Optionally remove existing handlers attached to j.u.l root logger
57 * SLF4JBridgeHandler.removeHandlersForRootLogger(); // (since SLF4J 1.6.5)
58
59 * // add SLF4JBridgeHandler to j.u.l's root logger, should be done once during
60 * // the initialization phase of your application
61 * SLF4JBridgeHandler.install();</pre>
62 * <p><b>Installation via <em>logging.properties</em> configuration file:</b></p>
63 * <pre>
64 * // register SLF4JBridgeHandler as handler for the j.u.l. root logger
65 * handlers = org.slf4j.bridge.SLF4JBridgeHandler</pre>
66 * <p>Once SLF4JBridgeHandler is installed, logging by j.u.l. loggers will be directed to
67 * SLF4J. Example: </p>
68 * <pre>
69 * import java.util.logging.Logger;
70 * ...
71 * // usual pattern: get a Logger and then log a message
72 * Logger julLogger = Logger.getLogger(&quot;org.wombat&quot;);
73 * julLogger.fine(&quot;hello world&quot;); // this will get redirected to SLF4J</pre>
74 *
75 * <p>Please note that translating a java.util.logging event into SLF4J incurs the
76 * cost of constructing {@link LogRecord} instance regardless of whether the
77 * SLF4J logger is disabled for the given level. <b>Consequently, j.u.l. to
78 * SLF4J translation can seriously increase the cost of disabled logging
79 * statements (60 fold or 6000% increase) and measurably impact the performance of enabled log
80 * statements (20% overall increase).</b> Please note that as of logback-version 0.9.25,
81 * it is possible to completely eliminate the 60 fold translation overhead for disabled
82 * log statements with the help of <a href="http://logback.qos.ch/manual/configuration.html#LevelChangePropagator">LevelChangePropagator</a>.
83 * </p>
84 *
85 * <p>If you are concerned about application performance, then use of <code>SLF4JBridgeHandler</code>
86 * is appropriate only if any one the following two conditions is true:</p>
87 * <ol>
88 * <li>few j.u.l. logging statements are in play</li>
89 * <li>LevelChangePropagator has been installed</li>
90 * </ol>
91 *
92 * @author Christian Stein
93 * @author Joern Huxhorn
94 * @author Ceki G&uuml;lc&uuml;
95 * @author Darryl Smith
96 * @since 1.5.1
97 */
98 public class SLF4JBridgeHandler extends Handler {
99
100 // The caller is java.util.logging.Logger
101 private static final String FQCN = java.util.logging.Logger.class.getName();
102 private static final String UNKNOWN_LOGGER_NAME = "unknown.jul.logger";
103
104 private static final int TRACE_LEVEL_THRESHOLD = Level.FINEST.intValue();
105 private static final int DEBUG_LEVEL_THRESHOLD = Level.FINE.intValue();
106 private static final int INFO_LEVEL_THRESHOLD = Level.INFO.intValue();
107 private static final int WARN_LEVEL_THRESHOLD = Level.WARNING.intValue();
108
109 /**
110 * Adds a SLF4JBridgeHandler instance to jul's root logger.
111 * <p/>
112 * <p/>
113 * This handler will redirect j.u.l. logging to SLF4J. However, only logs enabled
114 * in j.u.l. will be redirected. For example, if a log statement invoking a
115 * j.u.l. logger is disabled, then the corresponding non-event will <em>not</em>
116 * reach SLF4JBridgeHandler and cannot be redirected.
117 */
118 public static void install() {
119 LogManager.getLogManager().getLogger("").addHandler(new SLF4JBridgeHandler());
120 }
121
122 private static java.util.logging.Logger getRootLogger() {
123 return LogManager.getLogManager().getLogger("");
124 }
125
126 /**
127 * Removes previously installed SLF4JBridgeHandler instances. See also
128 * {@link #install()}.
129 *
130 * @throws SecurityException A <code>SecurityException</code> is thrown, if a security manager
131 * exists and if the caller does not have
132 * LoggingPermission("control").
133 */
134 public static void uninstall() throws SecurityException {
135 java.util.logging.Logger rootLogger = getRootLogger();
136 Handler[] handlers = rootLogger.getHandlers();
137 for (int i = 0; i < handlers.length; i++) {
138 if (handlers[i] instanceof SLF4JBridgeHandler) {
139 rootLogger.removeHandler(handlers[i]);
140 }
141 }
142 }
143
144 /**
145 * Returns true if SLF4JBridgeHandler has been previously installed, returns false otherwise.
146 *
147 * @return true if SLF4JBridgeHandler is already installed, false other wise
148 * @throws SecurityException
149 */
150 public static boolean isInstalled() throws SecurityException {
151 java.util.logging.Logger rootLogger = getRootLogger();
152 Handler[] handlers = rootLogger.getHandlers();
153 for (int i = 0; i < handlers.length; i++) {
154 if (handlers[i] instanceof SLF4JBridgeHandler) {
155 return true;
156 }
157 }
158 return false;
159 }
160
161 /**
162 * Invoking this method removes/unregisters/detaches all handlers currently attached to the root logger
163 * @since 1.6.5
164 */
165 public static void removeHandlersForRootLogger() {
166 java.util.logging.Logger rootLogger = getRootLogger();
167 java.util.logging.Handler[] handlers = rootLogger.getHandlers();
168 for (int i = 0; i < handlers.length; i++) {
169 rootLogger.removeHandler(handlers[i]);
170 }
171 }
172
173 /**
174 * Initialize this handler.
175 */
176 public SLF4JBridgeHandler() {
177 }
178
179 /**
180 * No-op implementation.
181 */
182 public void close() {
183 // empty
184 }
185
186 /**
187 * No-op implementation.
188 */
189 public void flush() {
190 // empty
191 }
192
193 /**
194 * Return the Logger instance that will be used for logging.
195 */
196 protected Logger getSLF4JLogger(LogRecord record) {
197 String name = record.getLoggerName();
198 if (name == null) {
199 name = UNKNOWN_LOGGER_NAME;
200 }
201 return LoggerFactory.getLogger(name);
202 }
203
204 protected void callLocationAwareLogger(LocationAwareLogger lal, LogRecord record) {
205 int julLevelValue = record.getLevel().intValue();
206 int slf4jLevel;
207
208 if (julLevelValue <= TRACE_LEVEL_THRESHOLD) {
209 slf4jLevel = LocationAwareLogger.TRACE_INT;
210 } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) {
211 slf4jLevel = LocationAwareLogger.DEBUG_INT;
212 } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) {
213 slf4jLevel = LocationAwareLogger.INFO_INT;
214 } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) {
215 slf4jLevel = LocationAwareLogger.WARN_INT;
216 } else {
217 slf4jLevel = LocationAwareLogger.ERROR_INT;
218 }
219 String i18nMessage = getMessageI18N(record);
220 lal.log(null, FQCN, slf4jLevel, i18nMessage, null, record.getThrown());
221 }
222
223 protected void callPlainSLF4JLogger(Logger slf4jLogger, LogRecord record) {
224 String i18nMessage = getMessageI18N(record);
225 int julLevelValue = record.getLevel().intValue();
226 if (julLevelValue <= TRACE_LEVEL_THRESHOLD) {
227 slf4jLogger.trace(i18nMessage, record.getThrown());
228 } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) {
229 slf4jLogger.debug(i18nMessage, record.getThrown());
230 } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) {
231 slf4jLogger.info(i18nMessage, record.getThrown());
232 } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) {
233 slf4jLogger.warn(i18nMessage, record.getThrown());
234 } else {
235 slf4jLogger.error(i18nMessage, record.getThrown());
236 }
237 }
238
239 /**
240 * Get the record's message, possibly via a resource bundle.
241 *
242 * @param record
243 * @return
244 */
245 private String getMessageI18N(LogRecord record) {
246 String message = record.getMessage();
247
248 if (message == null) {
249 return null;
250 }
251
252 ResourceBundle bundle = record.getResourceBundle();
253 if (bundle != null) {
254 try {
255 message = bundle.getString(message);
256 } catch (MissingResourceException e) {
257 }
258 }
259 Object[] params = record.getParameters();
260 // avoid formatting when there are no or 0 parameters. see also
261 // http://jira.qos.ch/browse/SLF4J-203
262 if (params != null && params.length > 0) {
263 try {
264 message = MessageFormat.format(message, params);
265 } catch (IllegalArgumentException e) {
266 // default to the same behavior as in java.util.logging.Formatter.formatMessage(LogRecord)
267 // see also http://jira.qos.ch/browse/SLF4J-337
268 return message;
269 }
270 }
271 return message;
272 }
273
274 /**
275 * Publish a LogRecord.
276 * <p/>
277 * The logging request was made initially to a Logger object, which
278 * initialized the LogRecord and forwarded it here.
279 * <p/>
280 * This handler ignores the Level attached to the LogRecord, as SLF4J cares
281 * about discarding log statements.
282 *
283 * @param record Description of the log event. A null record is silently ignored
284 * and is not published.
285 */
286 public void publish(LogRecord record) {
287 // Silently ignore null records.
288 if (record == null) {
289 return;
290 }
291
292 Logger slf4jLogger = getSLF4JLogger(record);
293 String message = record.getMessage(); // can be null!
294 // this is a check to avoid calling the underlying logging system
295 // with a null message. While it is legitimate to invoke j.u.l. with
296 // a null message, other logging frameworks do not support this.
297 // see also http://jira.qos.ch/browse/SLF4J-99
298 if (message == null) {
299 message = "";
300 }
301 if (slf4jLogger instanceof LocationAwareLogger) {
302 callLocationAwareLogger((LocationAwareLogger) slf4jLogger, record);
303 } else {
304 callPlainSLF4JLogger(slf4jLogger, record);
305 }
306 }
307
308 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import java.text.MessageFormat;
27 import java.util.MissingResourceException;
28 import java.util.ResourceBundle;
29 import java.util.logging.Handler;
30 import java.util.logging.Level;
31 import java.util.logging.LogManager;
32 import java.util.logging.LogRecord;
33
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.slf4j.spi.LocationAwareLogger;
37
38 // Based on http://jira.qos.ch/browse/SLF4J-30
39
40 /**
41 * <p>Bridge/route all JUL log records to the SLF4J API.</p>
42 * <p>Essentially, the idea is to install on the root logger an instance of
43 * <code>SLF4JBridgeHandler</code> as the sole JUL handler in the system. Subsequently, the
44 * SLF4JBridgeHandler instance will redirect all JUL log records are redirected
45 * to the SLF4J API based on the following mapping of levels:
46 * </p>
47 * <pre>
48 * FINEST -&gt; TRACE
49 * FINER -&gt; DEBUG
50 * FINE -&gt; DEBUG
51 * INFO -&gt; INFO
52 * WARNING -&gt; WARN
53 * SEVERE -&gt; ERROR</pre>
54 * <p><b>Programmatic installation:</b></p>
55 * <pre>
56 * // Optionally remove existing handlers attached to j.u.l root logger
57 * SLF4JBridgeHandler.removeHandlersForRootLogger(); // (since SLF4J 1.6.5)
58
59 * // add SLF4JBridgeHandler to j.u.l's root logger, should be done once during
60 * // the initialization phase of your application
61 * SLF4JBridgeHandler.install();</pre>
62 * <p><b>Installation via <em>logging.properties</em> configuration file:</b></p>
63 * <pre>
64 * // register SLF4JBridgeHandler as handler for the j.u.l. root logger
65 * handlers = org.slf4j.bridge.SLF4JBridgeHandler</pre>
66 * <p>Once SLF4JBridgeHandler is installed, logging by j.u.l. loggers will be directed to
67 * SLF4J. Example: </p>
68 * <pre>
69 * import java.util.logging.Logger;
70 * ...
71 * // usual pattern: get a Logger and then log a message
72 * Logger julLogger = Logger.getLogger(&quot;org.wombat&quot;);
73 * julLogger.fine(&quot;hello world&quot;); // this will get redirected to SLF4J</pre>
74 *
75 * <p>Please note that translating a java.util.logging event into SLF4J incurs the
76 * cost of constructing {@link LogRecord} instance regardless of whether the
77 * SLF4J logger is disabled for the given level. <b>Consequently, j.u.l. to
78 * SLF4J translation can seriously increase the cost of disabled logging
79 * statements (60 fold or 6000% increase) and measurably impact the performance of enabled log
80 * statements (20% overall increase).</b> Please note that as of logback-version 0.9.25,
81 * it is possible to completely eliminate the 60 fold translation overhead for disabled
82 * log statements with the help of <a href="http://logback.qos.ch/manual/configuration.html#LevelChangePropagator">LevelChangePropagator</a>.
83 * </p>
84 *
85 * <p>If you are concerned about application performance, then use of <code>SLF4JBridgeHandler</code>
86 * is appropriate only if any one the following two conditions is true:</p>
87 * <ol>
88 * <li>few j.u.l. logging statements are in play</li>
89 * <li>LevelChangePropagator has been installed</li>
90 * </ol>
91 *
92 * @author Christian Stein
93 * @author Joern Huxhorn
94 * @author Ceki G&uuml;lc&uuml;
95 * @author Darryl Smith
96 * @since 1.5.1
97 */
98 public class SLF4JBridgeHandler extends Handler {
99
100 // The caller is java.util.logging.Logger
101 private static final String FQCN = java.util.logging.Logger.class.getName();
102 private static final String UNKNOWN_LOGGER_NAME = "unknown.jul.logger";
103
104 private static final int TRACE_LEVEL_THRESHOLD = Level.FINEST.intValue();
105 private static final int DEBUG_LEVEL_THRESHOLD = Level.FINE.intValue();
106 private static final int INFO_LEVEL_THRESHOLD = Level.INFO.intValue();
107 private static final int WARN_LEVEL_THRESHOLD = Level.WARNING.intValue();
108
109 /**
110 * Adds a SLF4JBridgeHandler instance to jul's root logger.
111 * <p/>
112 * <p/>
113 * This handler will redirect j.u.l. logging to SLF4J. However, only logs enabled
114 * in j.u.l. will be redirected. For example, if a log statement invoking a
115 * j.u.l. logger is disabled, then the corresponding non-event will <em>not</em>
116 * reach SLF4JBridgeHandler and cannot be redirected.
117 */
118 public static void install() {
119 LogManager.getLogManager().getLogger("").addHandler(new SLF4JBridgeHandler());
120 }
121
122 private static java.util.logging.Logger getRootLogger() {
123 return LogManager.getLogManager().getLogger("");
124 }
125
126 /**
127 * Removes previously installed SLF4JBridgeHandler instances. See also
128 * {@link #install()}.
129 *
130 * @throws SecurityException A <code>SecurityException</code> is thrown, if a security manager
131 * exists and if the caller does not have
132 * LoggingPermission("control").
133 */
134 public static void uninstall() throws SecurityException {
135 java.util.logging.Logger rootLogger = getRootLogger();
136 Handler[] handlers = rootLogger.getHandlers();
137 for (int i = 0; i < handlers.length; i++) {
138 if (handlers[i] instanceof SLF4JBridgeHandler) {
139 rootLogger.removeHandler(handlers[i]);
140 }
141 }
142 }
143
144 /**
145 * Returns true if SLF4JBridgeHandler has been previously installed, returns false otherwise.
146 *
147 * @return true if SLF4JBridgeHandler is already installed, false other wise
148 * @throws SecurityException
149 */
150 public static boolean isInstalled() throws SecurityException {
151 java.util.logging.Logger rootLogger = getRootLogger();
152 Handler[] handlers = rootLogger.getHandlers();
153 for (int i = 0; i < handlers.length; i++) {
154 if (handlers[i] instanceof SLF4JBridgeHandler) {
155 return true;
156 }
157 }
158 return false;
159 }
160
161 /**
162 * Invoking this method removes/unregisters/detaches all handlers currently attached to the root logger
163 * @since 1.6.5
164 */
165 public static void removeHandlersForRootLogger() {
166 java.util.logging.Logger rootLogger = getRootLogger();
167 java.util.logging.Handler[] handlers = rootLogger.getHandlers();
168 for (int i = 0; i < handlers.length; i++) {
169 rootLogger.removeHandler(handlers[i]);
170 }
171 }
172
173 /**
174 * Initialize this handler.
175 */
176 public SLF4JBridgeHandler() {
177 }
178
179 /**
180 * No-op implementation.
181 */
182 public void close() {
183 // empty
184 }
185
186 /**
187 * No-op implementation.
188 */
189 public void flush() {
190 // empty
191 }
192
193 /**
194 * Return the Logger instance that will be used for logging.
195 */
196 protected Logger getSLF4JLogger(LogRecord record) {
197 String name = record.getLoggerName();
198 if (name == null) {
199 name = UNKNOWN_LOGGER_NAME;
200 }
201 return LoggerFactory.getLogger(name);
202 }
203
204 protected void callLocationAwareLogger(LocationAwareLogger lal, LogRecord record) {
205 int julLevelValue = record.getLevel().intValue();
206 int slf4jLevel;
207
208 if (julLevelValue <= TRACE_LEVEL_THRESHOLD) {
209 slf4jLevel = LocationAwareLogger.TRACE_INT;
210 } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) {
211 slf4jLevel = LocationAwareLogger.DEBUG_INT;
212 } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) {
213 slf4jLevel = LocationAwareLogger.INFO_INT;
214 } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) {
215 slf4jLevel = LocationAwareLogger.WARN_INT;
216 } else {
217 slf4jLevel = LocationAwareLogger.ERROR_INT;
218 }
219 String i18nMessage = getMessageI18N(record);
220 lal.log(null, FQCN, slf4jLevel, i18nMessage, null, record.getThrown());
221 }
222
223 protected void callPlainSLF4JLogger(Logger slf4jLogger, LogRecord record) {
224 String i18nMessage = getMessageI18N(record);
225 int julLevelValue = record.getLevel().intValue();
226 if (julLevelValue <= TRACE_LEVEL_THRESHOLD) {
227 slf4jLogger.trace(i18nMessage, record.getThrown());
228 } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) {
229 slf4jLogger.debug(i18nMessage, record.getThrown());
230 } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) {
231 slf4jLogger.info(i18nMessage, record.getThrown());
232 } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) {
233 slf4jLogger.warn(i18nMessage, record.getThrown());
234 } else {
235 slf4jLogger.error(i18nMessage, record.getThrown());
236 }
237 }
238
239 /**
240 * Get the record's message, possibly via a resource bundle.
241 *
242 * @param record
243 * @return
244 */
245 private String getMessageI18N(LogRecord record) {
246 String message = record.getMessage();
247
248 if (message == null) {
249 return null;
250 }
251
252 ResourceBundle bundle = record.getResourceBundle();
253 if (bundle != null) {
254 try {
255 message = bundle.getString(message);
256 } catch (MissingResourceException e) {
257 }
258 }
259 Object[] params = record.getParameters();
260 // avoid formatting when there are no or 0 parameters. see also
261 // http://jira.qos.ch/browse/SLF4J-203
262 if (params != null && params.length > 0) {
263 try {
264 message = MessageFormat.format(message, params);
265 } catch (IllegalArgumentException e) {
266 // default to the same behavior as in java.util.logging.Formatter.formatMessage(LogRecord)
267 // see also http://jira.qos.ch/browse/SLF4J-337
268 return message;
269 }
270 }
271 return message;
272 }
273
274 /**
275 * Publish a LogRecord.
276 * <p/>
277 * The logging request was made initially to a Logger object, which
278 * initialized the LogRecord and forwarded it here.
279 * <p/>
280 * This handler ignores the Level attached to the LogRecord, as SLF4J cares
281 * about discarding log statements.
282 *
283 * @param record Description of the log event. A null record is silently ignored
284 * and is not published.
285 */
286 public void publish(LogRecord record) {
287 // Silently ignore null records.
288 if (record == null) {
289 return;
290 }
291
292 Logger slf4jLogger = getSLF4JLogger(record);
293 String message = record.getMessage(); // can be null!
294 // this is a check to avoid calling the underlying logging system
295 // with a null message. While it is legitimate to invoke j.u.l. with
296 // a null message, other logging frameworks do not support this.
297 // see also http://jira.qos.ch/browse/SLF4J-99
298 if (message == null) {
299 message = "";
300 }
301 if (slf4jLogger instanceof LocationAwareLogger) {
302 callLocationAwareLogger((LocationAwareLogger) slf4jLogger, record);
303 } else {
304 callPlainSLF4JLogger(slf4jLogger, record);
305 }
306 }
307
308 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9
10 <p>Bridge/route all JUL log records to the SLF4J API.</p>
11
12 <hr/>
13 </body>
14 </html>
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9
10 <p>Bridge/route all JUL log records to the SLF4J API.</p>
11
12 <hr/>
13 </body>
14 </html>
0 Bundle-ManifestVersion: 2
1 Bundle-SymbolicName: jul.to.slf4j
2 Bundle-Name: jul-to-slf4j
3 Bundle-Vendor: SLF4J.ORG
4 Bundle-RequiredExecutionEnvironment: J2SE-1.5
5 Export-Package: org.slf4j.bridge;version=${parsedVersion.osgiVersion};uses:="org.slf4j,org.slf4j.spi"
6 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},org.slf4j.spi;version=${parsedVersion.osgiVersion}
0 Bundle-ManifestVersion: 2
1 Bundle-SymbolicName: jul.to.slf4j
2 Bundle-Name: jul-to-slf4j
3 Bundle-Vendor: SLF4J.ORG
4 Bundle-RequiredExecutionEnvironment: J2SE-1.5
5 Export-Package: org.slf4j.bridge;version=${parsedVersion.osgiVersion};uses:="org.slf4j,org.slf4j.spi"
6 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},org.slf4j.spi;version=${parsedVersion.osgiVersion}
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.apache.log4j.AppenderSkeleton;
30 import org.apache.log4j.spi.LoggingEvent;
31
32 public class ListAppender extends AppenderSkeleton {
33
34 public List<LoggingEvent> list = new ArrayList<LoggingEvent>();
35
36 public boolean extractLocationInfo = false;
37
38 protected void append(LoggingEvent event) {
39 list.add(event);
40 if (extractLocationInfo) {
41 event.getLocationInformation();
42 }
43 }
44
45 public void close() {
46 }
47
48 public boolean requiresLayout() {
49 return false;
50 }
51
52 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.apache.log4j.AppenderSkeleton;
30 import org.apache.log4j.spi.LoggingEvent;
31
32 public class ListAppender extends AppenderSkeleton {
33
34 public List<LoggingEvent> list = new ArrayList<LoggingEvent>();
35
36 public boolean extractLocationInfo = false;
37
38 protected void append(LoggingEvent event) {
39 list.add(event);
40 if (extractLocationInfo) {
41 event.getLocationInformation();
42 }
43 }
44
45 public void close() {
46 }
47
48 public boolean requiresLayout() {
49 return false;
50 }
51
52 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import java.util.logging.Handler;
27 import java.util.logging.LogManager;
28
29 import org.apache.log4j.FileAppender;
30 import org.apache.log4j.PatternLayout;
31 import org.junit.After;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.slf4j.LoggerFactory;
35
36 public class SLF4JBridgeHandlerPerfTest {
37
38 static String LOGGER_NAME = "yay";
39 static int RUN_LENGTH = 100 * 1000;
40
41 // set to false to test enabled logging performance
42 boolean disabledLogger = true;
43
44 FileAppender fileAppender;
45 org.apache.log4j.Logger log4jRoot;
46 java.util.logging.Logger julRootLogger = LogManager.getLogManager().getLogger("");
47
48 java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(LOGGER_NAME);
49 org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(LOGGER_NAME);
50
51 Handler[] existingHandlers;
52
53 @Before
54 public void setUp() throws Exception {
55 fileAppender = new FileAppender(new PatternLayout("%r [%t] %p %c %x - %m%n"), "target/test-output/toto.log");
56
57 existingHandlers = julRootLogger.getHandlers();
58 for (int i = 0; i < existingHandlers.length; i++) {
59 julRootLogger.removeHandler(existingHandlers[i]);
60 }
61 log4jRoot = org.apache.log4j.Logger.getRootLogger();
62 log4jRoot.addAppender(fileAppender);
63 }
64
65 @After
66 public void tearDown() throws Exception {
67 SLF4JBridgeHandler.uninstall();
68 fileAppender.close();
69 log4jRoot.getLoggerRepository().resetConfiguration();
70 for (int i = 0; i < existingHandlers.length; i++) {
71 julRootLogger.addHandler(existingHandlers[i]);
72 }
73 }
74
75 double julLoggerLoop() {
76 long start = System.nanoTime();
77 for (int i = 0; i < RUN_LENGTH; i++) {
78 julLogger.info("jul");
79 }
80 long end = System.nanoTime();
81 return (end - start) * 1.0 / RUN_LENGTH;
82 }
83
84 double slf4jLoggerLoop() {
85 long start = System.nanoTime();
86 for (int i = 0; i < RUN_LENGTH; i++) {
87 slf4jLogger.info("slf4j");
88 }
89 long end = System.nanoTime();
90 return (end - start) * 1.0 / RUN_LENGTH;
91 }
92
93 @Test
94 public void testPerf() {
95 SLF4JBridgeHandler.install();
96
97 if (disabledLogger) {
98 log4jRoot.setLevel(org.apache.log4j.Level.ERROR);
99 }
100 julLoggerLoop();
101 double julAvg = julLoggerLoop();
102 System.out.println("Average cost per call (JUL->SLF4J->log4j): " + julAvg + " nanos");
103
104 slf4jLoggerLoop();
105 double slf4jAvg = slf4jLoggerLoop();
106 System.out.println("Average cost per call (SLF4J->log4j): " + slf4jAvg + " nanos");
107 System.out.println("Ratio " + (julAvg / slf4jAvg));
108 }
109 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import java.util.logging.Handler;
27 import java.util.logging.LogManager;
28
29 import org.apache.log4j.FileAppender;
30 import org.apache.log4j.PatternLayout;
31 import org.junit.After;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.slf4j.LoggerFactory;
35
36 public class SLF4JBridgeHandlerPerfTest {
37
38 static String LOGGER_NAME = "yay";
39 static int RUN_LENGTH = 100 * 1000;
40
41 // set to false to test enabled logging performance
42 boolean disabledLogger = true;
43
44 FileAppender fileAppender;
45 org.apache.log4j.Logger log4jRoot;
46 java.util.logging.Logger julRootLogger = LogManager.getLogManager().getLogger("");
47
48 java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(LOGGER_NAME);
49 org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(LOGGER_NAME);
50
51 Handler[] existingHandlers;
52
53 @Before
54 public void setUp() throws Exception {
55 fileAppender = new FileAppender(new PatternLayout("%r [%t] %p %c %x - %m%n"), "target/test-output/toto.log");
56
57 existingHandlers = julRootLogger.getHandlers();
58 for (int i = 0; i < existingHandlers.length; i++) {
59 julRootLogger.removeHandler(existingHandlers[i]);
60 }
61 log4jRoot = org.apache.log4j.Logger.getRootLogger();
62 log4jRoot.addAppender(fileAppender);
63 }
64
65 @After
66 public void tearDown() throws Exception {
67 SLF4JBridgeHandler.uninstall();
68 fileAppender.close();
69 log4jRoot.getLoggerRepository().resetConfiguration();
70 for (int i = 0; i < existingHandlers.length; i++) {
71 julRootLogger.addHandler(existingHandlers[i]);
72 }
73 }
74
75 double julLoggerLoop() {
76 long start = System.nanoTime();
77 for (int i = 0; i < RUN_LENGTH; i++) {
78 julLogger.info("jul");
79 }
80 long end = System.nanoTime();
81 return (end - start) * 1.0 / RUN_LENGTH;
82 }
83
84 double slf4jLoggerLoop() {
85 long start = System.nanoTime();
86 for (int i = 0; i < RUN_LENGTH; i++) {
87 slf4jLogger.info("slf4j");
88 }
89 long end = System.nanoTime();
90 return (end - start) * 1.0 / RUN_LENGTH;
91 }
92
93 @Test
94 public void testPerf() {
95 SLF4JBridgeHandler.install();
96
97 if (disabledLogger) {
98 log4jRoot.setLevel(org.apache.log4j.Level.ERROR);
99 }
100 julLoggerLoop();
101 double julAvg = julLoggerLoop();
102 System.out.println("Average cost per call (JUL->SLF4J->log4j): " + julAvg + " nanos");
103
104 slf4jLoggerLoop();
105 double slf4jAvg = slf4jLoggerLoop();
106 System.out.println("Average cost per call (SLF4J->log4j): " + slf4jAvg + " nanos");
107 System.out.println("Ratio " + (julAvg / slf4jAvg));
108 }
109 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.text.MessageFormat;
29 import java.util.ResourceBundle;
30 import java.util.logging.Level;
31
32 import org.apache.log4j.spi.LocationInfo;
33 import org.apache.log4j.spi.LoggingEvent;
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37
38 public class SLF4JBridgeHandlerTest {
39
40 static String LOGGER_NAME = "yay";
41
42 ListAppender listAppender = new ListAppender();
43 org.apache.log4j.Logger log4jRoot;
44 java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger("yay");
45
46 @Before
47 public void setUp() throws Exception {
48 listAppender.extractLocationInfo = true;
49 log4jRoot = org.apache.log4j.Logger.getRootLogger();
50 log4jRoot.addAppender(listAppender);
51 log4jRoot.setLevel(org.apache.log4j.Level.TRACE);
52 }
53
54 @After
55 public void tearDown() throws Exception {
56 SLF4JBridgeHandler.uninstall();
57 log4jRoot.getLoggerRepository().resetConfiguration();
58 }
59
60 @Test
61 public void testSmoke() {
62 SLF4JBridgeHandler.install();
63 String msg = "msg";
64 julLogger.info(msg);
65 assertEquals(1, listAppender.list.size());
66 LoggingEvent le = (LoggingEvent) listAppender.list.get(0);
67 assertEquals(LOGGER_NAME, le.getLoggerName());
68 assertEquals(msg, le.getMessage());
69
70 // get the location info in the event.
71 // Note that this must have been computed previously
72 // within an appender for the following assertion to
73 // work properly
74 LocationInfo li = le.getLocationInformation();
75 System.out.println(li.fullInfo);
76 assertEquals("SLF4JBridgeHandlerTest.java", li.getFileName());
77 assertEquals("testSmoke", li.getMethodName());
78 }
79
80 @Test
81 public void testLevels() {
82 SLF4JBridgeHandler.install();
83 String msg = "msg";
84 julLogger.setLevel(Level.ALL);
85
86 julLogger.finest(msg);
87 julLogger.finer(msg);
88 julLogger.fine(msg);
89 julLogger.info(msg);
90 julLogger.warning(msg);
91 julLogger.severe(msg);
92
93 assertEquals(6, listAppender.list.size());
94 int i = 0;
95 assertLevel(i++, org.apache.log4j.Level.TRACE);
96 assertLevel(i++, org.apache.log4j.Level.DEBUG);
97 assertLevel(i++, org.apache.log4j.Level.DEBUG);
98 assertLevel(i++, org.apache.log4j.Level.INFO);
99 assertLevel(i++, org.apache.log4j.Level.WARN);
100 assertLevel(i++, org.apache.log4j.Level.ERROR);
101 }
102
103 @Test
104 public void testLogWithResourceBundle() {
105 SLF4JBridgeHandler.install();
106
107 String resourceBundleName = "org.slf4j.bridge.testLogStrings";
108 ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName);
109 String resourceKey = "resource_key";
110 String expectedMsg = bundle.getString(resourceKey);
111 String msg = resourceKey;
112
113 java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("yay", resourceBundleName);
114
115 julResourceBundleLogger.info(msg);
116 assertEquals(1, listAppender.list.size());
117 LoggingEvent le = (LoggingEvent) listAppender.list.get(0);
118 assertEquals(LOGGER_NAME, le.getLoggerName());
119 assertEquals(expectedMsg, le.getMessage());
120 }
121
122 @Test
123 public void testLogWithResourceBundleWithParameters() {
124 SLF4JBridgeHandler.install();
125
126 String resourceBundleName = "org.slf4j.bridge.testLogStrings";
127 ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName);
128
129 java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("foo", resourceBundleName);
130
131 String resourceKey1 = "resource_key_1";
132 String expectedMsg1 = bundle.getString(resourceKey1);
133 julResourceBundleLogger.info(resourceKey1); // 1st log
134
135 String resourceKey2 = "resource_key_2";
136 Object[] params2 = new Object[] { "foo", "bar" };
137 String expectedMsg2 = MessageFormat.format(bundle.getString(resourceKey2), params2);
138 julResourceBundleLogger.log(Level.INFO, resourceKey2, params2); // 2nd log
139
140 String resourceKey3 = "invalidKey {0}";
141 Object[] params3 = new Object[] { "John" };
142 String expectedMsg3 = MessageFormat.format(resourceKey3, params3);
143 julResourceBundleLogger.log(Level.INFO, resourceKey3, params3); // 3rd log
144
145 julLogger.log(Level.INFO, resourceKey3, params3); // 4th log
146
147 assertEquals(4, listAppender.list.size());
148
149 LoggingEvent le = null;
150
151 le = (LoggingEvent) listAppender.list.get(0);
152 assertEquals("foo", le.getLoggerName());
153 assertEquals(expectedMsg1, le.getMessage());
154
155 le = (LoggingEvent) listAppender.list.get(1);
156 assertEquals("foo", le.getLoggerName());
157 assertEquals(expectedMsg2, le.getMessage());
158
159 le = (LoggingEvent) listAppender.list.get(2);
160 assertEquals("foo", le.getLoggerName());
161 assertEquals(expectedMsg3, le.getMessage());
162
163 le = (LoggingEvent) listAppender.list.get(3);
164 assertEquals("yay", le.getLoggerName());
165 assertEquals(expectedMsg3, le.getMessage());
166 }
167
168 @Test
169 public void testLogWithPlaceholderNoParameters() {
170 SLF4JBridgeHandler.install();
171 String msg = "msg {non-number-string}";
172 julLogger.logp(Level.INFO, "SLF4JBridgeHandlerTest", "testLogWithPlaceholderNoParameters", msg, new Object[0]);
173
174 assertEquals(1, listAppender.list.size());
175 LoggingEvent le = (LoggingEvent) listAppender.list.get(0);
176 assertEquals(LOGGER_NAME, le.getLoggerName());
177 assertEquals(msg, le.getMessage());
178 }
179
180 // See http://jira.qos.ch/browse/SLF4J-337
181
182 @Test
183 public void illFormattedInputShouldBeReturnedAsIs() {
184 SLF4JBridgeHandler.install();
185 String msg = "foo {18=bad} {0}";
186
187 julLogger.log(Level.INFO, msg, "ignored parameter due to IllegalArgumentException");
188 assertEquals(1, listAppender.list.size());
189 LoggingEvent le = (LoggingEvent) listAppender.list.get(0);
190 assertEquals(msg, le.getMessage());
191 }
192
193 void assertLevel(int index, org.apache.log4j.Level expectedLevel) {
194 LoggingEvent le = (LoggingEvent) listAppender.list.get(index);
195 assertEquals(expectedLevel, le.getLevel());
196 }
197 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.text.MessageFormat;
29 import java.util.ResourceBundle;
30 import java.util.logging.Level;
31
32 import org.apache.log4j.spi.LocationInfo;
33 import org.apache.log4j.spi.LoggingEvent;
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37
38 public class SLF4JBridgeHandlerTest {
39
40 static String LOGGER_NAME = "yay";
41
42 ListAppender listAppender = new ListAppender();
43 org.apache.log4j.Logger log4jRoot;
44 java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger("yay");
45
46 @Before
47 public void setUp() throws Exception {
48 listAppender.extractLocationInfo = true;
49 log4jRoot = org.apache.log4j.Logger.getRootLogger();
50 log4jRoot.addAppender(listAppender);
51 log4jRoot.setLevel(org.apache.log4j.Level.TRACE);
52 }
53
54 @After
55 public void tearDown() throws Exception {
56 SLF4JBridgeHandler.uninstall();
57 log4jRoot.getLoggerRepository().resetConfiguration();
58 }
59
60 @Test
61 public void testSmoke() {
62 SLF4JBridgeHandler.install();
63 String msg = "msg";
64 julLogger.info(msg);
65 assertEquals(1, listAppender.list.size());
66 LoggingEvent le = (LoggingEvent) listAppender.list.get(0);
67 assertEquals(LOGGER_NAME, le.getLoggerName());
68 assertEquals(msg, le.getMessage());
69
70 // get the location info in the event.
71 // Note that this must have been computed previously
72 // within an appender for the following assertion to
73 // work properly
74 LocationInfo li = le.getLocationInformation();
75 System.out.println(li.fullInfo);
76 assertEquals("SLF4JBridgeHandlerTest.java", li.getFileName());
77 assertEquals("testSmoke", li.getMethodName());
78 }
79
80 @Test
81 public void testLevels() {
82 SLF4JBridgeHandler.install();
83 String msg = "msg";
84 julLogger.setLevel(Level.ALL);
85
86 julLogger.finest(msg);
87 julLogger.finer(msg);
88 julLogger.fine(msg);
89 julLogger.info(msg);
90 julLogger.warning(msg);
91 julLogger.severe(msg);
92
93 assertEquals(6, listAppender.list.size());
94 int i = 0;
95 assertLevel(i++, org.apache.log4j.Level.TRACE);
96 assertLevel(i++, org.apache.log4j.Level.DEBUG);
97 assertLevel(i++, org.apache.log4j.Level.DEBUG);
98 assertLevel(i++, org.apache.log4j.Level.INFO);
99 assertLevel(i++, org.apache.log4j.Level.WARN);
100 assertLevel(i++, org.apache.log4j.Level.ERROR);
101 }
102
103 @Test
104 public void testLogWithResourceBundle() {
105 SLF4JBridgeHandler.install();
106
107 String resourceBundleName = "org.slf4j.bridge.testLogStrings";
108 ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName);
109 String resourceKey = "resource_key";
110 String expectedMsg = bundle.getString(resourceKey);
111 String msg = resourceKey;
112
113 java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("yay", resourceBundleName);
114
115 julResourceBundleLogger.info(msg);
116 assertEquals(1, listAppender.list.size());
117 LoggingEvent le = (LoggingEvent) listAppender.list.get(0);
118 assertEquals(LOGGER_NAME, le.getLoggerName());
119 assertEquals(expectedMsg, le.getMessage());
120 }
121
122 @Test
123 public void testLogWithResourceBundleWithParameters() {
124 SLF4JBridgeHandler.install();
125
126 String resourceBundleName = "org.slf4j.bridge.testLogStrings";
127 ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName);
128
129 java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("foo", resourceBundleName);
130
131 String resourceKey1 = "resource_key_1";
132 String expectedMsg1 = bundle.getString(resourceKey1);
133 julResourceBundleLogger.info(resourceKey1); // 1st log
134
135 String resourceKey2 = "resource_key_2";
136 Object[] params2 = new Object[] { "foo", "bar" };
137 String expectedMsg2 = MessageFormat.format(bundle.getString(resourceKey2), params2);
138 julResourceBundleLogger.log(Level.INFO, resourceKey2, params2); // 2nd log
139
140 String resourceKey3 = "invalidKey {0}";
141 Object[] params3 = new Object[] { "John" };
142 String expectedMsg3 = MessageFormat.format(resourceKey3, params3);
143 julResourceBundleLogger.log(Level.INFO, resourceKey3, params3); // 3rd log
144
145 julLogger.log(Level.INFO, resourceKey3, params3); // 4th log
146
147 assertEquals(4, listAppender.list.size());
148
149 LoggingEvent le = null;
150
151 le = (LoggingEvent) listAppender.list.get(0);
152 assertEquals("foo", le.getLoggerName());
153 assertEquals(expectedMsg1, le.getMessage());
154
155 le = (LoggingEvent) listAppender.list.get(1);
156 assertEquals("foo", le.getLoggerName());
157 assertEquals(expectedMsg2, le.getMessage());
158
159 le = (LoggingEvent) listAppender.list.get(2);
160 assertEquals("foo", le.getLoggerName());
161 assertEquals(expectedMsg3, le.getMessage());
162
163 le = (LoggingEvent) listAppender.list.get(3);
164 assertEquals("yay", le.getLoggerName());
165 assertEquals(expectedMsg3, le.getMessage());
166 }
167
168 @Test
169 public void testLogWithPlaceholderNoParameters() {
170 SLF4JBridgeHandler.install();
171 String msg = "msg {non-number-string}";
172 julLogger.logp(Level.INFO, "SLF4JBridgeHandlerTest", "testLogWithPlaceholderNoParameters", msg, new Object[0]);
173
174 assertEquals(1, listAppender.list.size());
175 LoggingEvent le = (LoggingEvent) listAppender.list.get(0);
176 assertEquals(LOGGER_NAME, le.getLoggerName());
177 assertEquals(msg, le.getMessage());
178 }
179
180 // See http://jira.qos.ch/browse/SLF4J-337
181
182 @Test
183 public void illFormattedInputShouldBeReturnedAsIs() {
184 SLF4JBridgeHandler.install();
185 String msg = "foo {18=bad} {0}";
186
187 julLogger.log(Level.INFO, msg, "ignored parameter due to IllegalArgumentException");
188 assertEquals(1, listAppender.list.size());
189 LoggingEvent le = (LoggingEvent) listAppender.list.get(0);
190 assertEquals(msg, le.getMessage());
191 }
192
193 void assertLevel(int index, org.apache.log4j.Level expectedLevel) {
194 LoggingEvent le = (LoggingEvent) listAppender.list.get(index);
195 assertEquals(expectedLevel, le.getLevel());
196 }
197 }
0 resource_key=msg
1 resource_key_1=msg
2 resource_key_2=msg {0} {1}
0 resource_key=msg
1 resource_key_1=msg
2 resource_key_2=msg {0} {1}
0 <project name="testing-log4j-bridge" default="usage" basedir=".">
1
2 <property name="lbversion" value="0.9.8-SNAPSHOT" />
3 <property name="slf4jversion" value="1.4.2" />
4 <property name="source.home" value="./src/main/java/" />
5 <property name="javac.dest.12" value="./target/classes12/" />
6 <property name="javac.dest.13" value="./target/classes13/" />
7 <property name="lib" value="./lib" />
8
9 <property name="deprecation" value="on" />
10
11 <path id="basic.classpath">
12 <pathelement location="${source.home}" />
13 <pathelement location="${lib}/junit-3.8.1.jar" />
14 </path>
15
16 <path id="log4j12.classpath">
17 <path refid="basic.classpath" />
18 <pathelement location="${javac.dest.12}" />
19 <pathelement location="${lib}/log4j-1.2.14.jar" />
20 </path>
21
22 <path id="log4j13.classpath">
23 <path refid="basic.classpath" />
24 <pathelement location="${javac.dest.13}" />
25 <pathelement location="${lib}/log4j-1.3alpha-8.jar" />
26 </path>
27
28 <path id="los.classpath">
29 <path refid="basic.classpath" />
30 <pathelement location="${lib}/log4j-over-slf4j-${slf4jversion}.jar" />
31 <pathelement location="${lib}/logback-classic-${lbversion}.jar" />
32 <pathelement location="${lib}/logback-core-${lbversion}.jar" />
33 <pathelement location="${lib}/slf4j-api-${slf4jversion}.jar" />
34 </path>
35
36 <!-- ================================================================= -->
37 <!-- Default target -->
38 <!-- ================================================================= -->
39 <target name="usage">
40 <echo>
41 These are some of the targets supported by this ANT build scpript:
42
43 all - run all available tests
44 refresh - copy required jar files to the lib directory
45 </echo>
46 </target>
47
48 <delete>
49 <fileset dir="." includes="**/*.bak"/>
50 </delete>
51
52 <target name="refresh">
53 <delete>
54 <fileset dir="lib">
55 <include name="logback-*.jar"/>
56 <include name="log4j-bridge-*.jar"/>
57 </fileset>
58 </delete>
59 <copy file="../../slf4j-api/target/slf4j-api-${slf4jversion}.jar" todir="lib/"/>
60 <copy file="../target/log4j-over-slf4j-${slf4jversion}.jar" todir="lib/"/>
61
62 </target>
63
64
65 <target name="init">
66 <mkdir dir="${javac.dest.12}" />
67 <mkdir dir="${javac.dest.13}" />
68 </target>
69
70 <target name="clean">
71 <delete>
72 <fileset dir="${javac.dest.12}" includes="**" />
73 <fileset dir="${javac.dest.13}" includes="**" />
74 </delete>
75 </target>
76
77 <target name="build_log4j12" depends="init">
78 <javac srcdir="${source.home}"
79 destdir="${javac.dest.12}"
80 includes="**/Log4j12Calls.java"
81 deprecation="${deprecation}" debug="on">
82 <classpath refid="log4j12.classpath" />
83 </javac>
84 </target>
85
86 <target name="build_log4j13" depends="init">
87 <javac srcdir="${source.home}"
88 destdir="${javac.dest.13}"
89 includes="**/Log4j13Calls.java" deprecation="${deprecation}" debug="on">
90 <classpath refid="log4j13.classpath" />
91 </javac>
92 </target>
93
94 <target name="build_loggerTest" depends="init">
95 <javac srcdir="${source.home}"
96 destdir="${javac.dest.12}"
97 includes="**/LoggerTest.java"
98 deprecation="${deprecation}" debug="on">
99 <classpath refid="los.classpath" />
100 </javac>
101 </target>
102
103 <!-- ================================================================= -->
104 <!-- Run tests -->
105 <!-- ================================================================= -->
106 <target name="all" depends="test12, test13, loggerTest" />
107
108
109 <target name="loggerTest" depends="build_loggerTest">
110 <junit printsummary="yes" fork="yes" haltonfailure="yes">
111 <classpath refid="los.classpath" />
112 <classpath location="${javac.dest.12}" />
113 <formatter type="plain" usefile="false" />
114 <test name="test.LoggerTest" />
115 </junit>
116 </target>
117
118 <target name="test12" depends="build_log4j12">
119 <junit printsummary="yes" fork="yes" haltonfailure="yes">
120 <classpath refid="los.classpath" />
121 <classpath location="${javac.dest.12}" />
122 <formatter type="plain" usefile="false" />
123 <test name="test.Log4j12Calls" />
124 </junit>
125 </target>
126
127 <target name="test13" depends="build_log4j13">
128 <junit printsummary="yes" fork="yes" haltonfailure="yes">
129 <classpath refid="los.classpath" />
130 <classpath location="${javac.dest.13}" />
131 <formatter type="plain" usefile="false" />
132 <test name="test.Log4j13Calls" />
133 </junit>
134 </target>
135
136 </project>
0
1 This directory is used to test the module against various log4j calls.
2 Two test cases simulate the typical calls that one can find in an application
3 that uses either log4j 1.2.x, or log4j 1.3.x.
4
5 In the same directory is a build.xml file that uses ant to
6 compile the test cases with the corresponding log4j version,
7 and to runs these tests without log4j in the classpath but with
8 logback jars instead.
9
10 To run the tests, one must have ant installed. Issuing the following command,
11 once in the compatibility directory will launch the tests:
12
13 ant all
14
15 To obtain more information about the use of the log4j-over-slf4j module,
16 please visit http://www..slf4j.org/log4j-over-slf4j.html
0 package test;
1
2 public class DummyObject {
3
4 public String toString() {
5 return "dummy";
6 }
7 }
0 /**
1 * Logback: the reliable, generic, fast and flexible logging framework.
2 *
3 * Copyright (C) 1999-2006, QOS.ch
4 *
5 * This library is free software, you can redistribute it and/or modify it under
6 * the terms of the GNU Lesser General Public License as published by the Free
7 * Software Foundation.
8 */
9 package test;
10
11 import junit.framework.TestCase;
12
13 import org.apache.log4j.Logger;
14 import org.apache.log4j.MDC;
15
16 /**
17 *
18 * A test case that issues the typical calls
19 * that an application using log4j 1.2 would do.
20 *
21 * @author Ceki G&uuml;lc&uuml;
22 * @author S&eacute;bastien Pennec
23 */
24 public class Log4j12Calls extends TestCase {
25 public static final Logger logger = Logger.getLogger(Log4j12Calls.class);
26
27 public void testLog() {
28 MDC.put("key", "value1");
29
30 logger.trace("Trace level can be noisy");
31 logger.debug("Entering application");
32 logger.info("Violets are blue");
33 logger.warn("Here is a warning");
34 logger.error("Exiting application", new Exception("just testing"));
35
36 MDC.remove("key");
37 }
38 }
0 /**
1 * Logback: the reliable, generic, fast and flexible logging framework.
2 *
3 * Copyright (C) 1999-2006, QOS.ch
4 *
5 * This library is free software, you can redistribute it and/or modify it under
6 * the terms of the GNU Lesser General Public License as published by the Free
7 * Software Foundation.
8 */
9
10 package test;
11
12 import junit.framework.TestCase;
13
14 import org.apache.log4j.Logger;
15 import org.apache.log4j.MDC;
16
17 /**
18 *
19 * A test case that issues the typical calls
20 * that an application using log4j 1.3 would do.
21 *
22 * @author Ceki G&uuml;lc&uuml;
23 * @author S&eacute;bastien Pennec
24 */
25
26 public class Log4j13Calls extends TestCase {
27 public static final Logger logger = Logger.getLogger(Log4j12Calls.class);
28
29 public void testLog() {
30 MDC.put("key", "value1");
31
32 logger.trace("Trace level can be noisy");
33 logger.debug("Entering application");
34 logger.info("Violets are blue");
35 logger.warn("Here is a warning");
36 logger.info("The answer is {}.", new Integer(42));
37 logger.info("Number: {} and another one: {}.", new Integer(42), new Integer(24));
38
39 logger.error("Exiting application", new Exception("just testing"));
40
41 MDC.remove("key");
42
43 MDC.clear();
44 }
45 }
0 package test;
1
2 import junit.framework.TestCase;
3
4 import org.slf4j.LoggerFactory;
5
6 import ch.qos.logback.classic.LoggerContext;
7 import ch.qos.logback.classic.spi.LoggingEvent;
8 import ch.qos.logback.core.read.ListAppender;
9 import org.apache.log4j.Level;
10
11 /**
12 * A class that tests the invocation of the org.apache.log4j.Logger class that
13 * belongs to the log4j-bridge package
14 *
15 * @author S&eacute;bastien Pennec
16 * @author Ceki G&uuml;lc&uuml;
17 */
18
19 public class LoggerTest extends TestCase {
20
21 LoggerContext context;
22 ListAppender<LoggingEvent> appender;
23 ch.qos.logback.classic.Logger logbackLogger;
24 org.apache.log4j.Logger log4jLogger;
25
26 public void setUp() throws Exception {
27 context = (LoggerContext) LoggerFactory.getILoggerFactory();
28 context.shutdownAndReset();
29 appender = new ListAppender<LoggingEvent>();
30 appender.setContext(context);
31 appender.setName("listAppender");
32 appender.start();
33 ch.qos.logback.classic.Logger lbLogger = context
34 .getLogger(LoggerContext.ROOT_NAME);
35 lbLogger.addAppender(appender);
36
37 log4jLogger = org.apache.log4j.Logger.getLogger(LoggerTest.class);
38 logbackLogger = context.getLogger(LoggerTest.class);
39 super.setUp();
40 }
41
42 public void tearDown() throws Exception {
43 appender.stop();
44 context.stop();
45 appender = null;
46 context = null;
47 logbackLogger = null;
48 log4jLogger = null;
49 super.tearDown();
50 }
51
52 public void testLogWithObjectMessages() {
53 LoggingEvent event;
54
55 log4jLogger.debug("test");
56 event = appender.list.get(0);
57 assertEquals("test", event.getMessage());
58 appender.list.clear();
59
60 log4jLogger.debug(null);
61 event = appender.list.get(0);
62 assertEquals(null, event.getMessage());
63 appender.list.clear();
64
65 DummyObject dummy = new DummyObject();
66 log4jLogger.debug(dummy);
67 event = appender.list.get(0);
68 assertEquals(dummy.toString(), event.getMessage());
69 appender.list.clear();
70 }
71
72 public void testIsEnabledAPI() {
73 assertFalse(log4jLogger.isTraceEnabled());
74 assertTrue(log4jLogger.isDebugEnabled());
75 assertTrue(log4jLogger.isInfoEnabled());
76 assertTrue(log4jLogger.isWarnEnabled());
77 assertTrue(log4jLogger.isErrorEnabled());
78 }
79
80 public void testPrintAPI() {
81 Exception e = new Exception("just testing");
82
83 log4jLogger.trace(null);
84 assertEquals(1, appender.list.size());
85 appender.list.clear();
86
87 log4jLogger.debug(null);
88 assertEquals(1, appender.list.size());
89 appender.list.clear();
90
91 log4jLogger.debug("debug message");
92 assertEquals(1, appender.list.size());
93 appender.list.clear();
94
95 log4jLogger.info(null);
96 assertEquals(1, appender.list.size());
97 appender.list.clear();
98
99 log4jLogger.info("info message");
100 assertEquals(1, appender.list.size());
101 appender.list.clear();
102
103 log4jLogger.warn(null);
104 assertEquals(1, appender.list.size());
105 appender.list.clear();
106
107 log4jLogger.warn("warn message");
108 assertEquals(1, appender.list.size());
109 appender.list.clear();
110
111 log4jLogger.error(null);
112 assertEquals(1, appender.list.size());
113 appender.list.clear();
114
115 log4jLogger.error("error message");
116 assertEquals(1, appender.list.size());
117 appender.list.clear();
118
119 log4jLogger.debug(null, e);
120 assertEquals(1, appender.list.size());
121 appender.list.clear();
122
123 log4jLogger.debug("debug message", e);
124 assertEquals(1, appender.list.size());
125 appender.list.clear();
126
127 log4jLogger.info(null, e);
128 assertEquals(1, appender.list.size());
129 appender.list.clear();
130
131 log4jLogger.info("info message", e);
132 assertEquals(1, appender.list.size());
133 appender.list.clear();
134
135 log4jLogger.warn(null, e);
136 assertEquals(1, appender.list.size());
137 appender.list.clear();
138
139 log4jLogger.warn("warn message", e);
140 assertEquals(1, appender.list.size());
141 appender.list.clear();
142
143 log4jLogger.error(null, e);
144 assertEquals(1, appender.list.size());
145 appender.list.clear();
146
147 log4jLogger.error("error message", e);
148 assertEquals(1, appender.list.size());
149 appender.list.clear();
150
151 }
152
153 public void testLogAPI() {
154 log4jLogger.log("x", Level.TRACE, "x", null);
155 assertEquals(0, appender.list.size());
156
157 log4jLogger.log("x", Level.DEBUG, "x", null);
158 log4jLogger.log("x", Level.INFO, "x", null);
159 log4jLogger.log("x", Level.WARN, "x", null);
160 log4jLogger.log("x", Level.ERROR, "x", null);
161 log4jLogger.log("x", Level.FATAL, "x", null);
162
163 assertEquals(5, appender.list.size());
164 appender.list.clear();
165
166 }
167
168 }
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12
13 <artifactId>log4j-over-slf4j</artifactId>
14 <packaging>jar</packaging>
15 <name>Log4j Implemented Over SLF4J</name>
16 <description>Log4j implemented over SLF4J</description>
17
18 <url>http://www.slf4j.org</url>
19
20 <licenses>
21 <license>
22 <name>Apache Software Licenses</name>
23 <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
24 </license>
25 </licenses>
26
27 <dependencies>
28 <dependency>
29 <groupId>org.slf4j</groupId>
30 <artifactId>slf4j-api</artifactId>
31 </dependency>
32 <dependency>
33 <groupId>org.slf4j</groupId>
34 <artifactId>slf4j-jdk14</artifactId>
35 <scope>test</scope>
36 </dependency>
37 </dependencies>
38
39 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12
13 <artifactId>log4j-over-slf4j</artifactId>
14 <packaging>jar</packaging>
15 <name>Log4j Implemented Over SLF4J</name>
16 <description>Log4j implemented over SLF4J</description>
17
18 <url>http://www.slf4j.org</url>
19
20 <licenses>
21 <license>
22 <name>Apache Software Licenses</name>
23 <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
24 </license>
25 </licenses>
26
27 <dependencies>
28 <dependency>
29 <groupId>org.slf4j</groupId>
30 <artifactId>slf4j-api</artifactId>
31 </dependency>
32 <dependency>
33 <groupId>org.slf4j</groupId>
34 <artifactId>slf4j-jdk14</artifactId>
35 <scope>test</scope>
36 </dependency>
37 </dependencies>
38
39 </project>
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.Filter;
19 import org.apache.log4j.spi.ErrorHandler;
20 import org.apache.log4j.spi.LoggingEvent;
21
22 /**
23 * Implement this interface for your own strategies for outputting log
24 * statements.
25 *
26 * @author Ceki G&uuml;lc&uuml;
27 */
28 public interface Appender {
29
30 /**
31 * Add a filter to the end of the filter list.
32 *
33 * @since 0.9.0
34 */
35 void addFilter(Filter newFilter);
36
37 /**
38 * Returns the head Filter. The Filters are organized in a linked list
39 * and so all Filters on this Appender are available through the result.
40 *
41 * @return the head Filter or null, if no Filters are present
42 * @since 1.1
43 */
44 public Filter getFilter();
45
46 /**
47 * Clear the list of filters by removing all the filters in it.
48 *
49 * @since 0.9.0
50 */
51 public void clearFilters();
52
53 /**
54 * Release any resources allocated within the appender such as file
55 * handles, network connections, etc.
56 * <p/>
57 * <p>It is a programming error to append to a closed appender.
58 *
59 * @since 0.8.4
60 */
61 public void close();
62
63 /**
64 * Log in <code>Appender</code> specific way. When appropriate,
65 * Loggers will call the <code>doAppend</code> method of appender
66 * implementations in order to log.
67 */
68 public void doAppend(LoggingEvent event);
69
70 /**
71 * Get the name of this appender. The name uniquely identifies the
72 * appender.
73 */
74 public String getName();
75
76 /**
77 * Set the {@link ErrorHandler} for this appender.
78 *
79 * @since 0.9.0
80 */
81 public void setErrorHandler(ErrorHandler errorHandler);
82
83 /**
84 * Returns the {@link ErrorHandler} for this appender.
85 *
86 * @since 1.1
87 */
88 public ErrorHandler getErrorHandler();
89
90 /**
91 * Set the {@link Layout} for this appender.
92 *
93 * @since 0.8.1
94 */
95 public void setLayout(Layout layout);
96
97 /**
98 * Returns this appenders layout.
99 *
100 * @since 1.1
101 */
102 public Layout getLayout();
103
104 /**
105 * Set the name of this appender. The name is used by other
106 * components to identify this appender.
107 *
108 * @since 0.8.1
109 */
110 public void setName(String name);
111
112 /**
113 * Configurators call this method to determine if the appender
114 * requires a layout. If this method returns <code>true</code>,
115 * meaning that layout is required, then the configurator will
116 * configure an layout using the configuration information at its
117 * disposal. If this method returns <code>false</code>, meaning that
118 * a layout is not required, then layout configuration will be
119 * skipped even if there is available layout configuration
120 * information at the disposal of the configurator.
121 * <p/>
122 * <p>In the rather exceptional case, where the appender
123 * implementation admits a layout but can also work without it, then
124 * the appender should return <code>true</code>.
125 *
126 * @since 0.8.4
127 */
128 public boolean requiresLayout();
129 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.Filter;
19 import org.apache.log4j.spi.ErrorHandler;
20 import org.apache.log4j.spi.LoggingEvent;
21
22 /**
23 * Implement this interface for your own strategies for outputting log
24 * statements.
25 *
26 * @author Ceki G&uuml;lc&uuml;
27 */
28 public interface Appender {
29
30 /**
31 * Add a filter to the end of the filter list.
32 *
33 * @since 0.9.0
34 */
35 void addFilter(Filter newFilter);
36
37 /**
38 * Returns the head Filter. The Filters are organized in a linked list
39 * and so all Filters on this Appender are available through the result.
40 *
41 * @return the head Filter or null, if no Filters are present
42 * @since 1.1
43 */
44 public Filter getFilter();
45
46 /**
47 * Clear the list of filters by removing all the filters in it.
48 *
49 * @since 0.9.0
50 */
51 public void clearFilters();
52
53 /**
54 * Release any resources allocated within the appender such as file
55 * handles, network connections, etc.
56 * <p/>
57 * <p>It is a programming error to append to a closed appender.
58 *
59 * @since 0.8.4
60 */
61 public void close();
62
63 /**
64 * Log in <code>Appender</code> specific way. When appropriate,
65 * Loggers will call the <code>doAppend</code> method of appender
66 * implementations in order to log.
67 */
68 public void doAppend(LoggingEvent event);
69
70 /**
71 * Get the name of this appender. The name uniquely identifies the
72 * appender.
73 */
74 public String getName();
75
76 /**
77 * Set the {@link ErrorHandler} for this appender.
78 *
79 * @since 0.9.0
80 */
81 public void setErrorHandler(ErrorHandler errorHandler);
82
83 /**
84 * Returns the {@link ErrorHandler} for this appender.
85 *
86 * @since 1.1
87 */
88 public ErrorHandler getErrorHandler();
89
90 /**
91 * Set the {@link Layout} for this appender.
92 *
93 * @since 0.8.1
94 */
95 public void setLayout(Layout layout);
96
97 /**
98 * Returns this appenders layout.
99 *
100 * @since 1.1
101 */
102 public Layout getLayout();
103
104 /**
105 * Set the name of this appender. The name is used by other
106 * components to identify this appender.
107 *
108 * @since 0.8.1
109 */
110 public void setName(String name);
111
112 /**
113 * Configurators call this method to determine if the appender
114 * requires a layout. If this method returns <code>true</code>,
115 * meaning that layout is required, then the configurator will
116 * configure an layout using the configuration information at its
117 * disposal. If this method returns <code>false</code>, meaning that
118 * a layout is not required, then layout configuration will be
119 * skipped even if there is available layout configuration
120 * information at the disposal of the configurator.
121 * <p/>
122 * <p>In the rather exceptional case, where the appender
123 * implementation admits a layout but can also work without it, then
124 * the appender should return <code>true</code>.
125 *
126 * @since 0.8.4
127 */
128 public boolean requiresLayout();
129 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 import org.apache.log4j.spi.OptionHandler;
18
19 public class AppenderSkeleton implements OptionHandler {
20
21 public void setLayout(Layout layout) {
22 }
23
24 public void setName(String name) {
25 }
26
27 public void activateOptions() {
28 }
29
30 public void setThreshold(Priority threshold) {
31 }
32 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 import org.apache.log4j.spi.OptionHandler;
18
19 public class AppenderSkeleton implements OptionHandler {
20
21 public void setLayout(Layout layout) {
22 }
23
24 public void setName(String name) {
25 }
26
27 public void activateOptions() {
28 }
29
30 public void setThreshold(Priority threshold) {
31 }
32 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 /**
19 * A minimal (nop) implementation of BasicConfigurator.
20 */
21 public class BasicConfigurator {
22 public static void configure() {
23 }
24
25 public static void configure(Appender appender) {
26 }
27
28 public static void resetConfiguration() {
29 }
30 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 /**
19 * A minimal (nop) implementation of BasicConfigurator.
20 */
21 public class BasicConfigurator {
22 public static void configure() {
23 }
24
25 public static void configure(Appender appender) {
26 }
27
28 public static void resetConfiguration() {
29 }
30 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.helpers.NullEnumeration;
19 import org.slf4j.LoggerFactory;
20 import org.slf4j.Marker;
21 import org.slf4j.MarkerFactory;
22 import org.slf4j.spi.LocationAwareLogger;
23
24 import java.util.Enumeration;
25
26 /**
27 * <p>
28 * This class is a minimal implementation of the original
29 * <code>org.apache.log4j.Category</code> class (as found in log4j 1.2) by
30 * delegation of all calls to a {@link org.slf4j.Logger} instance.
31 * </p>
32 *
33 * <p>
34 * Log4j's <code>trace</code>, <code>debug()</code>, <code>info()</code>,
35 * <code>warn()</code>, <code>error()</code> printing methods are directly
36 * mapped to their SLF4J equivalents. Log4j's <code>fatal()</code> printing
37 * method is mapped to SLF4J's <code>error()</code> method with a FATAL marker.
38 *
39 * @author S&eacute;bastien Pennec
40 * @author Ceki G&uuml;lc&uuml;
41 */
42 @SuppressWarnings("rawtypes")
43 public class Category {
44
45 private static final String CATEGORY_FQCN = Category.class.getName();
46
47 private String name;
48
49 protected org.slf4j.Logger slf4jLogger;
50 private org.slf4j.spi.LocationAwareLogger locationAwareLogger;
51
52 private static Marker FATAL_MARKER = MarkerFactory.getMarker("FATAL");
53
54 Category(String name) {
55 this.name = name;
56 slf4jLogger = LoggerFactory.getLogger(name);
57 if (slf4jLogger instanceof LocationAwareLogger) {
58 locationAwareLogger = (LocationAwareLogger) slf4jLogger;
59 }
60 }
61
62 public static Category getInstance(Class clazz) {
63 return Log4jLoggerFactory.getLogger(clazz.getName());
64 }
65
66 public static Category getInstance(String name) {
67 return Log4jLoggerFactory.getLogger(name);
68 }
69
70 public final Category getParent() {
71 return null;
72 }
73
74 /**
75 * Returns the obvious.
76 *
77 * @return
78 */
79 public String getName() {
80 return name;
81 }
82
83 public Appender getAppender(String name) {
84 return null;
85 }
86
87 public Enumeration getAllAppenders() {
88 return NullEnumeration.getInstance();
89 }
90
91 /**
92 * Return the level in effect for this category/logger.
93 *
94 * <p>
95 * The result is computed by simulation.
96 *
97 * @return
98 */
99 public Level getEffectiveLevel() {
100 if (slf4jLogger.isTraceEnabled()) {
101 return Level.TRACE;
102 }
103 if (slf4jLogger.isDebugEnabled()) {
104 return Level.DEBUG;
105 }
106 if (slf4jLogger.isInfoEnabled()) {
107 return Level.INFO;
108 }
109 if (slf4jLogger.isWarnEnabled()) {
110 return Level.WARN;
111 }
112 return Level.ERROR;
113 }
114
115 /**
116 * Returns the assigned {@link Level}, if any, for this Category. This
117 * implementation always returns null.
118 *
119 * @return Level - the assigned Level, can be <code>null</code>.
120 */
121 final public Level getLevel() {
122 return null;
123 }
124
125 /**
126 * @deprecated Please use {@link #getLevel} instead.
127 */
128 final public Level getPriority() {
129 return null;
130 }
131
132 /**
133 * Delegates to {@link org.slf4j.Logger#isDebugEnabled} method in SLF4J
134 */
135 public boolean isDebugEnabled() {
136 return slf4jLogger.isDebugEnabled();
137 }
138
139 /**
140 * Delegates to {@link org.slf4j.Logger#isInfoEnabled} method in SLF4J
141 */
142 public boolean isInfoEnabled() {
143 return slf4jLogger.isInfoEnabled();
144 }
145
146 /**
147 * Delegates to {@link org.slf4j.Logger#isWarnEnabled} method in SLF4J
148 */
149 public boolean isWarnEnabled() {
150 return slf4jLogger.isWarnEnabled();
151 }
152
153 /**
154 * Delegates to {@link org.slf4j.Logger#isErrorEnabled} method in SLF4J
155 */
156 public boolean isErrorEnabled() {
157 return slf4jLogger.isErrorEnabled();
158 }
159
160 /**
161 * Determines whether the priority passed as parameter is enabled in the
162 * underlying SLF4J logger. Each log4j priority is mapped directly to its
163 * SLF4J equivalent, except for FATAL which is mapped as ERROR.
164 *
165 * @param p
166 * the priority to check against
167 * @return true if this logger is enabled for the given level, false
168 * otherwise.
169 */
170 public boolean isEnabledFor(Priority p) {
171 switch (p.level) {
172 case Level.TRACE_INT:
173 return slf4jLogger.isTraceEnabled();
174 case Level.DEBUG_INT:
175 return slf4jLogger.isDebugEnabled();
176 case Level.INFO_INT:
177 return slf4jLogger.isInfoEnabled();
178 case Level.WARN_INT:
179 return slf4jLogger.isWarnEnabled();
180 case Level.ERROR_INT:
181 return slf4jLogger.isErrorEnabled();
182 case Priority.FATAL_INT:
183 return slf4jLogger.isErrorEnabled();
184 }
185 return false;
186 }
187
188 void differentiatedLog(Marker marker, String fqcn, int level, Object message, Throwable t) {
189
190 String m = convertToString(message);
191 if (locationAwareLogger != null) {
192 locationAwareLogger.log(marker, fqcn, level, m, null, t);
193 } else {
194 switch (level) {
195 case LocationAwareLogger.TRACE_INT:
196 slf4jLogger.trace(marker, m);
197 break;
198 case LocationAwareLogger.DEBUG_INT:
199 slf4jLogger.debug(marker, m);
200 break;
201 case LocationAwareLogger.INFO_INT:
202 slf4jLogger.info(marker, m);
203 break;
204 case LocationAwareLogger.WARN_INT:
205 slf4jLogger.warn(marker, m);
206 break;
207 case LocationAwareLogger.ERROR_INT:
208 slf4jLogger.error(marker, m);
209 break;
210 }
211 }
212 }
213
214 /**
215 * Delegates to {@link org.slf4j.Logger#debug(String)} method of SLF4J.
216 */
217 public void debug(Object message) {
218 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.DEBUG_INT, message, null);
219 }
220
221 /**
222 * Delegates to {@link org.slf4j.Logger#debug(String,Throwable)} method in
223 * SLF4J.
224 */
225 public void debug(Object message, Throwable t) {
226 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.DEBUG_INT, message, t);
227 }
228
229 /**
230 * Delegates to {@link org.slf4j.Logger#info(String)} method in SLF4J.
231 */
232 public void info(Object message) {
233 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.INFO_INT, message, null);
234 }
235
236 /**
237 * Delegates to {@link org.slf4j.Logger#info(String,Throwable)} method in
238 * SLF4J.
239 */
240 public void info(Object message, Throwable t) {
241 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.INFO_INT, message, t);
242 }
243
244 /**
245 * Delegates to {@link org.slf4j.Logger#warn(String)} method in SLF4J.
246 */
247 public void warn(Object message) {
248 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.WARN_INT, message, null);
249 }
250
251 /**
252 * Delegates to {@link org.slf4j.Logger#warn(String,Throwable)} method in
253 * SLF4J.
254 */
255 public void warn(Object message, Throwable t) {
256 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.WARN_INT, message, t);
257 }
258
259 /**
260 * Delegates to {@link org.slf4j.Logger#error(String)} method in SLF4J.
261 */
262 public void error(Object message) {
263 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, null);
264 }
265
266 /**
267 * Delegates to {@link org.slf4j.Logger#error(String,Throwable)} method in
268 * SLF4J.
269 */
270 public void error(Object message, Throwable t) {
271 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, t);
272 }
273
274 /**
275 * Delegates to {@link org.slf4j.Logger#error(String)} method in SLF4J.
276 */
277 public void fatal(Object message) {
278 differentiatedLog(FATAL_MARKER, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, null);
279 }
280
281 /**
282 * Delegates to {@link org.slf4j.Logger#error(String,Throwable)} method in
283 * SLF4J. In addition, the call is marked with a marker named "FATAL".
284 */
285 public void fatal(Object message, Throwable t) {
286 differentiatedLog(FATAL_MARKER, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, t);
287 }
288
289 protected void forcedLog(String FQCN, Priority p, Object msg, Throwable t) {
290 log(FQCN, p, msg, t);
291 }
292
293 // See also http://jira.qos.ch/browse/SLF4J-159
294 public void log(String FQCN, Priority p, Object msg, Throwable t) {
295 int levelInt = priorityToLevelInt(p);
296 differentiatedLog(null, FQCN, levelInt, msg, t);
297 }
298
299 public void log(Priority p, Object message, Throwable t) {
300 int levelInt = priorityToLevelInt(p);
301 differentiatedLog(null, CATEGORY_FQCN, levelInt, message, t);
302 }
303
304 public void log(Priority p, Object message) {
305 int levelInt = priorityToLevelInt(p);
306 differentiatedLog(null, CATEGORY_FQCN, levelInt, message, null);
307 }
308
309 private int priorityToLevelInt(Priority p) {
310 switch (p.level) {
311 case Level.TRACE_INT:
312 case Level.X_TRACE_INT:
313 return LocationAwareLogger.TRACE_INT;
314 case Priority.DEBUG_INT:
315 return LocationAwareLogger.DEBUG_INT;
316 case Priority.INFO_INT:
317 return LocationAwareLogger.INFO_INT;
318 case Priority.WARN_INT:
319 return LocationAwareLogger.WARN_INT;
320 case Priority.ERROR_INT:
321 return LocationAwareLogger.ERROR_INT;
322 case Priority.FATAL_INT:
323 return LocationAwareLogger.ERROR_INT;
324 default:
325 throw new IllegalStateException("Unknown Priority " + p);
326 }
327 }
328
329 protected final String convertToString(Object message) {
330 if (message == null) {
331 return (String) message;
332 } else {
333 return message.toString();
334 }
335 }
336
337 public void setAdditivity(boolean additive) {
338 // nothing to do
339 }
340
341 public void addAppender(Appender newAppender) {
342 // nothing to do
343 }
344
345 public void setLevel(Level level) {
346 // nothing to do
347 }
348
349 public boolean getAdditivity() {
350 return false;
351 }
352
353 public void assertLog(boolean assertion, String msg) {
354 if (!assertion)
355 error(msg);
356 }
357
358 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.helpers.NullEnumeration;
19 import org.slf4j.LoggerFactory;
20 import org.slf4j.Marker;
21 import org.slf4j.MarkerFactory;
22 import org.slf4j.spi.LocationAwareLogger;
23
24 import java.util.Enumeration;
25
26 /**
27 * <p>
28 * This class is a minimal implementation of the original
29 * <code>org.apache.log4j.Category</code> class (as found in log4j 1.2) by
30 * delegation of all calls to a {@link org.slf4j.Logger} instance.
31 * </p>
32 *
33 * <p>
34 * Log4j's <code>trace</code>, <code>debug()</code>, <code>info()</code>,
35 * <code>warn()</code>, <code>error()</code> printing methods are directly
36 * mapped to their SLF4J equivalents. Log4j's <code>fatal()</code> printing
37 * method is mapped to SLF4J's <code>error()</code> method with a FATAL marker.
38 *
39 * @author S&eacute;bastien Pennec
40 * @author Ceki G&uuml;lc&uuml;
41 */
42 @SuppressWarnings("rawtypes")
43 public class Category {
44
45 private static final String CATEGORY_FQCN = Category.class.getName();
46
47 private String name;
48
49 protected org.slf4j.Logger slf4jLogger;
50 private org.slf4j.spi.LocationAwareLogger locationAwareLogger;
51
52 private static Marker FATAL_MARKER = MarkerFactory.getMarker("FATAL");
53
54 Category(String name) {
55 this.name = name;
56 slf4jLogger = LoggerFactory.getLogger(name);
57 if (slf4jLogger instanceof LocationAwareLogger) {
58 locationAwareLogger = (LocationAwareLogger) slf4jLogger;
59 }
60 }
61
62 public static Category getInstance(Class clazz) {
63 return Log4jLoggerFactory.getLogger(clazz.getName());
64 }
65
66 public static Category getInstance(String name) {
67 return Log4jLoggerFactory.getLogger(name);
68 }
69
70 public final Category getParent() {
71 return null;
72 }
73
74 /**
75 * Returns the obvious.
76 *
77 * @return
78 */
79 public String getName() {
80 return name;
81 }
82
83 public Appender getAppender(String name) {
84 return null;
85 }
86
87 public Enumeration getAllAppenders() {
88 return NullEnumeration.getInstance();
89 }
90
91 /**
92 * Return the level in effect for this category/logger.
93 *
94 * <p>
95 * The result is computed by simulation.
96 *
97 * @return
98 */
99 public Level getEffectiveLevel() {
100 if (slf4jLogger.isTraceEnabled()) {
101 return Level.TRACE;
102 }
103 if (slf4jLogger.isDebugEnabled()) {
104 return Level.DEBUG;
105 }
106 if (slf4jLogger.isInfoEnabled()) {
107 return Level.INFO;
108 }
109 if (slf4jLogger.isWarnEnabled()) {
110 return Level.WARN;
111 }
112 return Level.ERROR;
113 }
114
115 /**
116 * Returns the assigned {@link Level}, if any, for this Category. This
117 * implementation always returns null.
118 *
119 * @return Level - the assigned Level, can be <code>null</code>.
120 */
121 final public Level getLevel() {
122 return null;
123 }
124
125 /**
126 * @deprecated Please use {@link #getLevel} instead.
127 */
128 final public Level getPriority() {
129 return null;
130 }
131
132 /**
133 * Delegates to {@link org.slf4j.Logger#isDebugEnabled} method in SLF4J
134 */
135 public boolean isDebugEnabled() {
136 return slf4jLogger.isDebugEnabled();
137 }
138
139 /**
140 * Delegates to {@link org.slf4j.Logger#isInfoEnabled} method in SLF4J
141 */
142 public boolean isInfoEnabled() {
143 return slf4jLogger.isInfoEnabled();
144 }
145
146 /**
147 * Delegates to {@link org.slf4j.Logger#isWarnEnabled} method in SLF4J
148 */
149 public boolean isWarnEnabled() {
150 return slf4jLogger.isWarnEnabled();
151 }
152
153 /**
154 * Delegates to {@link org.slf4j.Logger#isErrorEnabled} method in SLF4J
155 */
156 public boolean isErrorEnabled() {
157 return slf4jLogger.isErrorEnabled();
158 }
159
160 /**
161 * Determines whether the priority passed as parameter is enabled in the
162 * underlying SLF4J logger. Each log4j priority is mapped directly to its
163 * SLF4J equivalent, except for FATAL which is mapped as ERROR.
164 *
165 * @param p
166 * the priority to check against
167 * @return true if this logger is enabled for the given level, false
168 * otherwise.
169 */
170 public boolean isEnabledFor(Priority p) {
171 switch (p.level) {
172 case Level.TRACE_INT:
173 return slf4jLogger.isTraceEnabled();
174 case Level.DEBUG_INT:
175 return slf4jLogger.isDebugEnabled();
176 case Level.INFO_INT:
177 return slf4jLogger.isInfoEnabled();
178 case Level.WARN_INT:
179 return slf4jLogger.isWarnEnabled();
180 case Level.ERROR_INT:
181 return slf4jLogger.isErrorEnabled();
182 case Priority.FATAL_INT:
183 return slf4jLogger.isErrorEnabled();
184 }
185 return false;
186 }
187
188 void differentiatedLog(Marker marker, String fqcn, int level, Object message, Throwable t) {
189
190 String m = convertToString(message);
191 if (locationAwareLogger != null) {
192 locationAwareLogger.log(marker, fqcn, level, m, null, t);
193 } else {
194 switch (level) {
195 case LocationAwareLogger.TRACE_INT:
196 slf4jLogger.trace(marker, m);
197 break;
198 case LocationAwareLogger.DEBUG_INT:
199 slf4jLogger.debug(marker, m);
200 break;
201 case LocationAwareLogger.INFO_INT:
202 slf4jLogger.info(marker, m);
203 break;
204 case LocationAwareLogger.WARN_INT:
205 slf4jLogger.warn(marker, m);
206 break;
207 case LocationAwareLogger.ERROR_INT:
208 slf4jLogger.error(marker, m);
209 break;
210 }
211 }
212 }
213
214 /**
215 * Delegates to {@link org.slf4j.Logger#debug(String)} method of SLF4J.
216 */
217 public void debug(Object message) {
218 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.DEBUG_INT, message, null);
219 }
220
221 /**
222 * Delegates to {@link org.slf4j.Logger#debug(String,Throwable)} method in
223 * SLF4J.
224 */
225 public void debug(Object message, Throwable t) {
226 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.DEBUG_INT, message, t);
227 }
228
229 /**
230 * Delegates to {@link org.slf4j.Logger#info(String)} method in SLF4J.
231 */
232 public void info(Object message) {
233 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.INFO_INT, message, null);
234 }
235
236 /**
237 * Delegates to {@link org.slf4j.Logger#info(String,Throwable)} method in
238 * SLF4J.
239 */
240 public void info(Object message, Throwable t) {
241 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.INFO_INT, message, t);
242 }
243
244 /**
245 * Delegates to {@link org.slf4j.Logger#warn(String)} method in SLF4J.
246 */
247 public void warn(Object message) {
248 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.WARN_INT, message, null);
249 }
250
251 /**
252 * Delegates to {@link org.slf4j.Logger#warn(String,Throwable)} method in
253 * SLF4J.
254 */
255 public void warn(Object message, Throwable t) {
256 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.WARN_INT, message, t);
257 }
258
259 /**
260 * Delegates to {@link org.slf4j.Logger#error(String)} method in SLF4J.
261 */
262 public void error(Object message) {
263 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, null);
264 }
265
266 /**
267 * Delegates to {@link org.slf4j.Logger#error(String,Throwable)} method in
268 * SLF4J.
269 */
270 public void error(Object message, Throwable t) {
271 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, t);
272 }
273
274 /**
275 * Delegates to {@link org.slf4j.Logger#error(String)} method in SLF4J.
276 */
277 public void fatal(Object message) {
278 differentiatedLog(FATAL_MARKER, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, null);
279 }
280
281 /**
282 * Delegates to {@link org.slf4j.Logger#error(String,Throwable)} method in
283 * SLF4J. In addition, the call is marked with a marker named "FATAL".
284 */
285 public void fatal(Object message, Throwable t) {
286 differentiatedLog(FATAL_MARKER, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, t);
287 }
288
289 protected void forcedLog(String FQCN, Priority p, Object msg, Throwable t) {
290 log(FQCN, p, msg, t);
291 }
292
293 // See also http://jira.qos.ch/browse/SLF4J-159
294 public void log(String FQCN, Priority p, Object msg, Throwable t) {
295 int levelInt = priorityToLevelInt(p);
296 differentiatedLog(null, FQCN, levelInt, msg, t);
297 }
298
299 public void log(Priority p, Object message, Throwable t) {
300 int levelInt = priorityToLevelInt(p);
301 differentiatedLog(null, CATEGORY_FQCN, levelInt, message, t);
302 }
303
304 public void log(Priority p, Object message) {
305 int levelInt = priorityToLevelInt(p);
306 differentiatedLog(null, CATEGORY_FQCN, levelInt, message, null);
307 }
308
309 private int priorityToLevelInt(Priority p) {
310 switch (p.level) {
311 case Level.TRACE_INT:
312 case Level.X_TRACE_INT:
313 return LocationAwareLogger.TRACE_INT;
314 case Priority.DEBUG_INT:
315 return LocationAwareLogger.DEBUG_INT;
316 case Priority.INFO_INT:
317 return LocationAwareLogger.INFO_INT;
318 case Priority.WARN_INT:
319 return LocationAwareLogger.WARN_INT;
320 case Priority.ERROR_INT:
321 return LocationAwareLogger.ERROR_INT;
322 case Priority.FATAL_INT:
323 return LocationAwareLogger.ERROR_INT;
324 default:
325 throw new IllegalStateException("Unknown Priority " + p);
326 }
327 }
328
329 protected final String convertToString(Object message) {
330 if (message == null) {
331 return (String) message;
332 } else {
333 return message.toString();
334 }
335 }
336
337 public void setAdditivity(boolean additive) {
338 // nothing to do
339 }
340
341 public void addAppender(Appender newAppender) {
342 // nothing to do
343 }
344
345 public void setLevel(Level level) {
346 // nothing to do
347 }
348
349 public boolean getAdditivity() {
350 return false;
351 }
352
353 public void assertLog(boolean assertion, String msg) {
354 if (!assertion)
355 error(msg);
356 }
357
358 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class ConsoleAppender extends WriterAppender {
18
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class ConsoleAppender extends WriterAppender {
18
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class FileAppender extends WriterAppender {
18
19 public FileAppender() {
20 }
21
22 public FileAppender(Layout layout, String filename) {
23 }
24
25 public FileAppender(Layout layout, String filename, boolean append) {
26 }
27
28 public FileAppender(Layout layout, String filename, boolean append, boolean bufferedIO, int bufferSize) {
29 }
30 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class FileAppender extends WriterAppender {
18
19 public FileAppender() {
20 }
21
22 public FileAppender(Layout layout, String filename) {
23 }
24
25 public FileAppender(Layout layout, String filename, boolean append) {
26 }
27
28 public FileAppender(Layout layout, String filename, boolean append, boolean bufferedIO, int bufferSize) {
29 }
30 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Christian Trutz <christian.trutz@belaso.de>
17 package org.apache.log4j;
18
19 /**
20 * This class is a minimal implementation of the original Log4J class.
21 *
22 * @author Christian Trutz <christian.trutz@belaso.de>
23 * */
24 public class Layout {
25
26 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Christian Trutz <christian.trutz@belaso.de>
17 package org.apache.log4j;
18
19 /**
20 * This class is a minimal implementation of the original Log4J class.
21 *
22 * @author Christian Trutz <christian.trutz@belaso.de>
23 * */
24 public class Layout {
25
26 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Kitching Simon <Simon.Kitching@orange.ch>
17 // Nicholas Wolff
18
19 package org.apache.log4j;
20
21 import java.io.IOException;
22 import java.io.ObjectInputStream;
23 import java.io.ObjectOutputStream;
24 import java.io.ObjectStreamException;
25 import java.io.Serializable;
26
27 /**
28 Defines the minimum set of levels recognized by the system, that is
29 <code>OFF</code>, <code>FATAL</code>, <code>ERROR</code>,
30 <code>WARN</code>, <code>INFO</code>, <code>DEBUG</code> and
31 <code>ALL</code>.
32
33 <p>The <code>Level</code> class may be subclassed to define a larger
34 level set.
35
36 @author Ceki G&uuml;lc&uuml;
37
38 */
39 public class Level extends Priority implements Serializable {
40
41 /**
42 * TRACE level integer value.
43 * @since 1.2.12
44 */
45 public static final int TRACE_INT = 5000;
46
47 // match jboss' xlevel
48 public static final int X_TRACE_INT = DEBUG_INT - 100;
49
50 /**
51 The <code>OFF</code> has the highest possible rank and is
52 intended to turn off logging. */
53 final static public Level OFF = new Level(OFF_INT, "OFF", 0);
54
55 /**
56 The <code>FATAL</code> level designates very severe error
57 events that will presumably lead the application to abort.
58 */
59 final static public Level FATAL = new Level(FATAL_INT, "FATAL", 0);
60
61 /**
62 The <code>ERROR</code> level designates error events that
63 might still allow the application to continue running. */
64 final static public Level ERROR = new Level(ERROR_INT, "ERROR", 3);
65
66 /**
67 The <code>WARN</code> level designates potentially harmful situations.
68 */
69 final static public Level WARN = new Level(WARN_INT, "WARN", 4);
70
71 /**
72 The <code>INFO</code> level designates informational messages
73 that highlight the progress of the application at coarse-grained
74 level. */
75 final static public Level INFO = new Level(INFO_INT, "INFO", 6);
76
77 /**
78 The <code>DEBUG</code> Level designates fine-grained
79 informational events that are most useful to debug an
80 application. */
81 final static public Level DEBUG = new Level(DEBUG_INT, "DEBUG", 7);
82
83 /**
84 * The <code>TRACE</code> Level designates finer-grained
85 * informational events than the <code>DEBUG</code level.
86 * @since 1.2.12
87 */
88 public static final Level TRACE = new Level(TRACE_INT, "TRACE", 7);
89
90 /**
91 The <code>ALL</code> has the lowest possible rank and is intended to
92 turn on all logging. */
93 final static public Level ALL = new Level(ALL_INT, "ALL", 7);
94
95 /**
96 * Serialization version id.
97 */
98 static final long serialVersionUID = 3491141966387921974L;
99
100 /**
101 Instantiate a Level object.
102 */
103 protected Level(int level, String levelStr, int syslogEquivalent) {
104 super(level, levelStr, syslogEquivalent);
105 }
106
107 /**
108 Convert the string passed as argument to a level. If the
109 conversion fails, then this method returns {@link #DEBUG}.
110 */
111 public static Level toLevel(String sArg) {
112 return (Level) toLevel(sArg, Level.DEBUG);
113 }
114
115 /**
116 Convert an integer passed as argument to a level. If the
117 conversion fails, then this method returns {@link #DEBUG}.
118
119 */
120 public static Level toLevel(int val) {
121 return (Level) toLevel(val, Level.DEBUG);
122 }
123
124 /**
125 Convert an integer passed as argument to a level. If the
126 conversion fails, then this method returns the specified default.
127 */
128 public static Level toLevel(int val, Level defaultLevel) {
129 switch (val) {
130 case ALL_INT:
131 return ALL;
132 case DEBUG_INT:
133 return Level.DEBUG;
134 case INFO_INT:
135 return Level.INFO;
136 case WARN_INT:
137 return Level.WARN;
138 case ERROR_INT:
139 return Level.ERROR;
140 case FATAL_INT:
141 return Level.FATAL;
142 case OFF_INT:
143 return OFF;
144 case TRACE_INT:
145 return Level.TRACE;
146 default:
147 return defaultLevel;
148 }
149 }
150
151 /**
152 Convert the string passed as argument to a level. If the
153 conversion fails, then this method returns the value of
154 <code>defaultLevel</code>.
155 */
156 public static Level toLevel(String sArg, Level defaultLevel) {
157 if (sArg == null)
158 return defaultLevel;
159
160 String s = sArg.toUpperCase();
161
162 if (s.equals("ALL"))
163 return Level.ALL;
164 if (s.equals("DEBUG"))
165 return Level.DEBUG;
166 if (s.equals("INFO"))
167 return Level.INFO;
168 if (s.equals("WARN"))
169 return Level.WARN;
170 if (s.equals("ERROR"))
171 return Level.ERROR;
172 if (s.equals("FATAL"))
173 return Level.FATAL;
174 if (s.equals("OFF"))
175 return Level.OFF;
176 if (s.equals("TRACE"))
177 return Level.TRACE;
178 return defaultLevel;
179 }
180
181 /**
182 * Custom deserialization of Level.
183 * @param s serialization stream.
184 * @throws IOException if IO exception.
185 * @throws ClassNotFoundException if class not found.
186 */
187 private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException {
188 s.defaultReadObject();
189 level = s.readInt();
190 syslogEquivalent = s.readInt();
191 levelStr = s.readUTF();
192 if (levelStr == null) {
193 levelStr = "";
194 }
195 }
196
197 /**
198 * Serialize level.
199 * @param s serialization stream.
200 * @throws IOException if exception during serialization.
201 */
202 private void writeObject(final ObjectOutputStream s) throws IOException {
203 s.defaultWriteObject();
204 s.writeInt(level);
205 s.writeInt(syslogEquivalent);
206 s.writeUTF(levelStr);
207 }
208
209 /**
210 * Resolved deserialized level to one of the stock instances.
211 * May be overridden in classes derived from Level.
212 * @return resolved object.
213 * @throws ObjectStreamException if exception during resolution.
214 */
215 private Object readResolve() throws ObjectStreamException {
216 //
217 // if the deserialized object is exactly an instance of Level
218 //
219 if (getClass() == Level.class) {
220 return toLevel(level);
221 }
222 //
223 // extension of Level can't substitute stock item
224 //
225 return this;
226 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Kitching Simon <Simon.Kitching@orange.ch>
17 // Nicholas Wolff
18
19 package org.apache.log4j;
20
21 import java.io.IOException;
22 import java.io.ObjectInputStream;
23 import java.io.ObjectOutputStream;
24 import java.io.ObjectStreamException;
25 import java.io.Serializable;
26
27 /**
28 Defines the minimum set of levels recognized by the system, that is
29 <code>OFF</code>, <code>FATAL</code>, <code>ERROR</code>,
30 <code>WARN</code>, <code>INFO</code>, <code>DEBUG</code> and
31 <code>ALL</code>.
32
33 <p>The <code>Level</code> class may be subclassed to define a larger
34 level set.
35
36 @author Ceki G&uuml;lc&uuml;
37
38 */
39 public class Level extends Priority implements Serializable {
40
41 /**
42 * TRACE level integer value.
43 * @since 1.2.12
44 */
45 public static final int TRACE_INT = 5000;
46
47 // match jboss' xlevel
48 public static final int X_TRACE_INT = DEBUG_INT - 100;
49
50 /**
51 The <code>OFF</code> has the highest possible rank and is
52 intended to turn off logging. */
53 final static public Level OFF = new Level(OFF_INT, "OFF", 0);
54
55 /**
56 The <code>FATAL</code> level designates very severe error
57 events that will presumably lead the application to abort.
58 */
59 final static public Level FATAL = new Level(FATAL_INT, "FATAL", 0);
60
61 /**
62 The <code>ERROR</code> level designates error events that
63 might still allow the application to continue running. */
64 final static public Level ERROR = new Level(ERROR_INT, "ERROR", 3);
65
66 /**
67 The <code>WARN</code> level designates potentially harmful situations.
68 */
69 final static public Level WARN = new Level(WARN_INT, "WARN", 4);
70
71 /**
72 The <code>INFO</code> level designates informational messages
73 that highlight the progress of the application at coarse-grained
74 level. */
75 final static public Level INFO = new Level(INFO_INT, "INFO", 6);
76
77 /**
78 The <code>DEBUG</code> Level designates fine-grained
79 informational events that are most useful to debug an
80 application. */
81 final static public Level DEBUG = new Level(DEBUG_INT, "DEBUG", 7);
82
83 /**
84 * The <code>TRACE</code> Level designates finer-grained
85 * informational events than the <code>DEBUG</code level.
86 * @since 1.2.12
87 */
88 public static final Level TRACE = new Level(TRACE_INT, "TRACE", 7);
89
90 /**
91 The <code>ALL</code> has the lowest possible rank and is intended to
92 turn on all logging. */
93 final static public Level ALL = new Level(ALL_INT, "ALL", 7);
94
95 /**
96 * Serialization version id.
97 */
98 static final long serialVersionUID = 3491141966387921974L;
99
100 /**
101 Instantiate a Level object.
102 */
103 protected Level(int level, String levelStr, int syslogEquivalent) {
104 super(level, levelStr, syslogEquivalent);
105 }
106
107 /**
108 Convert the string passed as argument to a level. If the
109 conversion fails, then this method returns {@link #DEBUG}.
110 */
111 public static Level toLevel(String sArg) {
112 return (Level) toLevel(sArg, Level.DEBUG);
113 }
114
115 /**
116 Convert an integer passed as argument to a level. If the
117 conversion fails, then this method returns {@link #DEBUG}.
118
119 */
120 public static Level toLevel(int val) {
121 return (Level) toLevel(val, Level.DEBUG);
122 }
123
124 /**
125 Convert an integer passed as argument to a level. If the
126 conversion fails, then this method returns the specified default.
127 */
128 public static Level toLevel(int val, Level defaultLevel) {
129 switch (val) {
130 case ALL_INT:
131 return ALL;
132 case DEBUG_INT:
133 return Level.DEBUG;
134 case INFO_INT:
135 return Level.INFO;
136 case WARN_INT:
137 return Level.WARN;
138 case ERROR_INT:
139 return Level.ERROR;
140 case FATAL_INT:
141 return Level.FATAL;
142 case OFF_INT:
143 return OFF;
144 case TRACE_INT:
145 return Level.TRACE;
146 default:
147 return defaultLevel;
148 }
149 }
150
151 /**
152 Convert the string passed as argument to a level. If the
153 conversion fails, then this method returns the value of
154 <code>defaultLevel</code>.
155 */
156 public static Level toLevel(String sArg, Level defaultLevel) {
157 if (sArg == null)
158 return defaultLevel;
159
160 String s = sArg.toUpperCase();
161
162 if (s.equals("ALL"))
163 return Level.ALL;
164 if (s.equals("DEBUG"))
165 return Level.DEBUG;
166 if (s.equals("INFO"))
167 return Level.INFO;
168 if (s.equals("WARN"))
169 return Level.WARN;
170 if (s.equals("ERROR"))
171 return Level.ERROR;
172 if (s.equals("FATAL"))
173 return Level.FATAL;
174 if (s.equals("OFF"))
175 return Level.OFF;
176 if (s.equals("TRACE"))
177 return Level.TRACE;
178 return defaultLevel;
179 }
180
181 /**
182 * Custom deserialization of Level.
183 * @param s serialization stream.
184 * @throws IOException if IO exception.
185 * @throws ClassNotFoundException if class not found.
186 */
187 private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException {
188 s.defaultReadObject();
189 level = s.readInt();
190 syslogEquivalent = s.readInt();
191 levelStr = s.readUTF();
192 if (levelStr == null) {
193 levelStr = "";
194 }
195 }
196
197 /**
198 * Serialize level.
199 * @param s serialization stream.
200 * @throws IOException if exception during serialization.
201 */
202 private void writeObject(final ObjectOutputStream s) throws IOException {
203 s.defaultWriteObject();
204 s.writeInt(level);
205 s.writeInt(syslogEquivalent);
206 s.writeUTF(levelStr);
207 }
208
209 /**
210 * Resolved deserialized level to one of the stock instances.
211 * May be overridden in classes derived from Level.
212 * @return resolved object.
213 * @throws ObjectStreamException if exception during resolution.
214 */
215 private Object readResolve() throws ObjectStreamException {
216 //
217 // if the deserialized object is exactly an instance of Level
218 //
219 if (getClass() == Level.class) {
220 return toLevel(level);
221 }
222 //
223 // extension of Level can't substitute stock item
224 //
225 return this;
226 }
227227 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.LoggerFactory;
19
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ConcurrentMap;
22
23 /**
24 * This class is a factory that creates and maintains org.apache.log4j.Loggers
25 * wrapping org.slf4j.Loggers.
26 *
27 * It keeps a hashtable of all created org.apache.log4j.Logger instances so that
28 * all newly created instances are not duplicates of existing loggers.
29 *
30 * @author S&eacute;bastien Pennec
31 */
32 class Log4jLoggerFactory {
33
34 // String, Logger
35 private static ConcurrentMap<String, Logger> log4jLoggers = new ConcurrentHashMap<String, Logger>();
36
37 public static Logger getLogger(String name) {
38 org.apache.log4j.Logger instance = log4jLoggers.get(name);
39 if (instance != null) {
40 return instance;
41 } else {
42 Logger newInstance = new Logger(name);
43 Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance);
44 return oldInstance == null ? newInstance : oldInstance;
45 }
46 }
47
48 public static Logger getLogger(String name, LoggerFactory loggerFactory) {
49 org.apache.log4j.Logger instance = log4jLoggers.get(name);
50 if (instance != null) {
51 return instance;
52 } else {
53 Logger newInstance = loggerFactory.makeNewLoggerInstance(name);
54 Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance);
55 return oldInstance == null ? newInstance : oldInstance;
56 }
57 }
58 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.LoggerFactory;
19
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ConcurrentMap;
22
23 /**
24 * This class is a factory that creates and maintains org.apache.log4j.Loggers
25 * wrapping org.slf4j.Loggers.
26 *
27 * It keeps a hashtable of all created org.apache.log4j.Logger instances so that
28 * all newly created instances are not duplicates of existing loggers.
29 *
30 * @author S&eacute;bastien Pennec
31 */
32 class Log4jLoggerFactory {
33
34 // String, Logger
35 private static ConcurrentMap<String, Logger> log4jLoggers = new ConcurrentHashMap<String, Logger>();
36
37 public static Logger getLogger(String name) {
38 org.apache.log4j.Logger instance = log4jLoggers.get(name);
39 if (instance != null) {
40 return instance;
41 } else {
42 Logger newInstance = new Logger(name);
43 Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance);
44 return oldInstance == null ? newInstance : oldInstance;
45 }
46 }
47
48 public static Logger getLogger(String name, LoggerFactory loggerFactory) {
49 org.apache.log4j.Logger instance = log4jLoggers.get(name);
50 if (instance != null) {
51 return instance;
52 } else {
53 Logger newInstance = loggerFactory.makeNewLoggerInstance(name);
54 Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance);
55 return oldInstance == null ? newInstance : oldInstance;
56 }
57 }
58 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.LoggerFactory;
19
20 import java.util.Enumeration;
21 import java.util.Vector;
22
23 /**
24 * <p/>
25 * This class is a minimal implementation of the original
26 * <code>org.apache.log4j.LogManager</code> class (as found in log4j 1.2)
27 * delegating all calls to SLF4J.
28 * <p/>
29 * <p/>
30 * This implementation does <b>NOT</b> implement the setRepositorySelector(),
31 * getLoggerRepository(), exists(), getCurrentLoggers(), shutdown() and
32 * resetConfiguration() methods which do not have SLF4J equivalents.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 @SuppressWarnings("rawtypes")
37 public class LogManager {
38
39 public static Logger getRootLogger() {
40 return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
41 }
42
43 public static Logger getLogger(final String name) {
44 return Log4jLoggerFactory.getLogger(name);
45 }
46
47 public static Logger getLogger(final Class clazz) {
48 return Log4jLoggerFactory.getLogger(clazz.getName());
49 }
50
51 /**
52 * Returns a logger instance created by loggerFactory. This method was requested in
53 * <a href="http://jira.qos.ch/browse/SLF4J-225">SLF4J-225</a>. Note that
54 * log4j-over-slf4j does not ship with a LoggerFactory implementation. If this
55 * method is called, the caller must provide his/her own implementation.
56 *
57 * @param name the name of the desired logger
58 * @param loggerFactory an instance of {@link LoggerFactory}
59 * @return returns a logger instance created by loggerFactory
60 * @since 1.6.6
61 */
62 public static Logger getLogger(String name, LoggerFactory loggerFactory) {
63 return loggerFactory.makeNewLoggerInstance(name);
64 }
65
66 /**
67 * This bogus implementation returns an empty enumeration.
68 *
69 * @return
70 */
71 public static Enumeration getCurrentLoggers() {
72 return new Vector().elements();
73 }
74
75 /**
76 * Implemented as NOP.
77 */
78 public static void shutdown() {
79 }
80
81 /**
82 * Implemented as NOP.
83 */
84 public static void resetConfiguration() {
85 }
86 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.LoggerFactory;
19
20 import java.util.Enumeration;
21 import java.util.Vector;
22
23 /**
24 * <p/>
25 * This class is a minimal implementation of the original
26 * <code>org.apache.log4j.LogManager</code> class (as found in log4j 1.2)
27 * delegating all calls to SLF4J.
28 * <p/>
29 * <p/>
30 * This implementation does <b>NOT</b> implement the setRepositorySelector(),
31 * getLoggerRepository(), exists(), getCurrentLoggers(), shutdown() and
32 * resetConfiguration() methods which do not have SLF4J equivalents.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 @SuppressWarnings("rawtypes")
37 public class LogManager {
38
39 public static Logger getRootLogger() {
40 return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
41 }
42
43 public static Logger getLogger(final String name) {
44 return Log4jLoggerFactory.getLogger(name);
45 }
46
47 public static Logger getLogger(final Class clazz) {
48 return Log4jLoggerFactory.getLogger(clazz.getName());
49 }
50
51 /**
52 * Returns a logger instance created by loggerFactory. This method was requested in
53 * <a href="http://jira.qos.ch/browse/SLF4J-225">SLF4J-225</a>. Note that
54 * log4j-over-slf4j does not ship with a LoggerFactory implementation. If this
55 * method is called, the caller must provide his/her own implementation.
56 *
57 * @param name the name of the desired logger
58 * @param loggerFactory an instance of {@link LoggerFactory}
59 * @return returns a logger instance created by loggerFactory
60 * @since 1.6.6
61 */
62 public static Logger getLogger(String name, LoggerFactory loggerFactory) {
63 return loggerFactory.makeNewLoggerInstance(name);
64 }
65
66 /**
67 * This bogus implementation returns an empty enumeration.
68 *
69 * @return
70 */
71 public static Enumeration getCurrentLoggers() {
72 return new Vector().elements();
73 }
74
75 /**
76 * Implemented as NOP.
77 */
78 public static void shutdown() {
79 }
80
81 /**
82 * Implemented as NOP.
83 */
84 public static void resetConfiguration() {
85 }
86 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.LoggerFactory;
19 import org.slf4j.spi.LocationAwareLogger;
20
21 /**
22 * <p>
23 * This class is a minimal implementation of the original
24 * <code>org.apache.log4j.Logger</code> class (as found in log4j 1.2)
25 * delegating all calls to a {@link org.slf4j.Logger} instance.
26 * </p>
27 *
28 * @author Ceki G&uuml;lc&uuml;
29 * */
30 @SuppressWarnings("rawtypes")
31 public class Logger extends Category {
32
33 private static final String LOGGER_FQCN = Logger.class.getName();
34
35 protected Logger(String name) {
36 super(name);
37 }
38
39 public static Logger getLogger(String name) {
40 return Log4jLoggerFactory.getLogger(name);
41 }
42
43 public static Logger getLogger(String name, LoggerFactory loggerFactory) {
44 return Log4jLoggerFactory.getLogger(name, loggerFactory);
45 }
46
47 public static Logger getLogger(Class clazz) {
48 return getLogger(clazz.getName());
49 }
50
51 /**
52 * Does the obvious.
53 *
54 * @return
55 */
56 public static Logger getRootLogger() {
57 return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
58 }
59
60 /**
61 * Delegates to {@link org.slf4j.Logger#isTraceEnabled}
62 * method of SLF4J.
63 */
64 public boolean isTraceEnabled() {
65 return slf4jLogger.isTraceEnabled();
66 }
67
68 /**
69 * Delegates to {@link org.slf4j.Logger#trace(String)} method in SLF4J.
70 */
71 public void trace(Object message) {
72 differentiatedLog(null, LOGGER_FQCN, LocationAwareLogger.TRACE_INT, message, null);
73 }
74
75 /**
76 * Delegates to {@link org.slf4j.Logger#trace(String,Throwable)}
77 * method in SLF4J.
78 */
79 public void trace(Object message, Throwable t) {
80 differentiatedLog(null, LOGGER_FQCN, LocationAwareLogger.TRACE_INT, message, null);
81 }
82
83 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.LoggerFactory;
19 import org.slf4j.spi.LocationAwareLogger;
20
21 /**
22 * <p>
23 * This class is a minimal implementation of the original
24 * <code>org.apache.log4j.Logger</code> class (as found in log4j 1.2)
25 * delegating all calls to a {@link org.slf4j.Logger} instance.
26 * </p>
27 *
28 * @author Ceki G&uuml;lc&uuml;
29 * */
30 @SuppressWarnings("rawtypes")
31 public class Logger extends Category {
32
33 private static final String LOGGER_FQCN = Logger.class.getName();
34
35 protected Logger(String name) {
36 super(name);
37 }
38
39 public static Logger getLogger(String name) {
40 return Log4jLoggerFactory.getLogger(name);
41 }
42
43 public static Logger getLogger(String name, LoggerFactory loggerFactory) {
44 return Log4jLoggerFactory.getLogger(name, loggerFactory);
45 }
46
47 public static Logger getLogger(Class clazz) {
48 return getLogger(clazz.getName());
49 }
50
51 /**
52 * Does the obvious.
53 *
54 * @return
55 */
56 public static Logger getRootLogger() {
57 return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
58 }
59
60 /**
61 * Delegates to {@link org.slf4j.Logger#isTraceEnabled}
62 * method of SLF4J.
63 */
64 public boolean isTraceEnabled() {
65 return slf4jLogger.isTraceEnabled();
66 }
67
68 /**
69 * Delegates to {@link org.slf4j.Logger#trace(String)} method in SLF4J.
70 */
71 public void trace(Object message) {
72 differentiatedLog(null, LOGGER_FQCN, LocationAwareLogger.TRACE_INT, message, null);
73 }
74
75 /**
76 * Delegates to {@link org.slf4j.Logger#trace(String,Throwable)}
77 * method in SLF4J.
78 */
79 public void trace(Object message, Throwable t) {
80 differentiatedLog(null, LOGGER_FQCN, LocationAwareLogger.TRACE_INT, message, null);
81 }
82
83 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import java.util.Hashtable;
19 import java.util.Map;
20
21 public class MDC {
22
23 public static void put(String key, String value) {
24 org.slf4j.MDC.put(key, value);
25 }
26
27 public static void put(String key, Object value) {
28 if (value != null) {
29 put(key, value.toString());
30 } else {
31 put(key, null);
32 }
33 }
34
35 public static Object get(String key) {
36 return org.slf4j.MDC.get(key);
37 }
38
39 public static void remove(String key) {
40 org.slf4j.MDC.remove(key);
41 }
42
43 public static void clear() {
44 org.slf4j.MDC.clear();
45 }
46
47 /**
48 * This method is not part of the Log4J public API. However it
49 * has been called by other projects. This method is here temporarily
50 * until projects who are depending on this method release fixes.
51 */
52 @SuppressWarnings({ "rawtypes", "unchecked" })
53 @Deprecated
54 public static Hashtable getContext() {
55 Map map = org.slf4j.MDC.getCopyOfContextMap();
56
57 if (map != null) {
58 return new Hashtable(map);
59 } else {
60 return new Hashtable();
61 }
62 }
63 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import java.util.Hashtable;
19 import java.util.Map;
20
21 public class MDC {
22
23 public static void put(String key, String value) {
24 org.slf4j.MDC.put(key, value);
25 }
26
27 public static void put(String key, Object value) {
28 if (value != null) {
29 put(key, value.toString());
30 } else {
31 put(key, null);
32 }
33 }
34
35 public static Object get(String key) {
36 return org.slf4j.MDC.get(key);
37 }
38
39 public static void remove(String key) {
40 org.slf4j.MDC.remove(key);
41 }
42
43 public static void clear() {
44 org.slf4j.MDC.clear();
45 }
46
47 /**
48 * This method is not part of the Log4J public API. However it
49 * has been called by other projects. This method is here temporarily
50 * until projects who are depending on this method release fixes.
51 */
52 @SuppressWarnings({ "rawtypes", "unchecked" })
53 @Deprecated
54 public static Hashtable getContext() {
55 Map map = org.slf4j.MDC.getCopyOfContextMap();
56
57 if (map != null) {
58 return new Hashtable(map);
59 } else {
60 return new Hashtable();
61 }
62 }
63 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.slf4j.MDC;
19
20 import java.util.Stack;
21
22 /**
23 * A log4j's NDC implemented in terms of SLF4J MDC primitives.
24 *
25 * @since SLF4J 1.6.0
26 */
27
28 public class NDC {
29
30 public final static String PREFIX = "NDC";
31
32 public static void clear() {
33 int depth = getDepth();
34 for (int i = 0; i < depth; i++) {
35 String key = PREFIX + i;
36 MDC.remove(key);
37 }
38 }
39
40 @SuppressWarnings("rawtypes")
41 public static Stack cloneStack() {
42 return null;
43 }
44
45 @SuppressWarnings("rawtypes")
46 public static void inherit(Stack stack) {
47 }
48
49 static public String get() {
50 return null;
51 }
52
53 public static int getDepth() {
54 int i = 0;
55 while (true) {
56 String val = MDC.get(PREFIX + i);
57 if (val != null) {
58 i++;
59 } else {
60 break;
61 }
62 }
63 return i;
64 }
65
66 public static String pop() {
67 int next = getDepth();
68 if (next == 0) {
69 return "";
70 }
71 int last = next - 1;
72 String key = PREFIX + last;
73 String val = MDC.get(key);
74 MDC.remove(key);
75 return val;
76 }
77
78 public static String peek() {
79 int next = getDepth();
80 if (next == 0) {
81 return "";
82 }
83 int last = next - 1;
84 String key = PREFIX + last;
85 String val = MDC.get(key);
86 return val;
87 }
88
89 public static void push(String message) {
90 int next = getDepth();
91 MDC.put(PREFIX + next, message);
92 }
93
94 static public void remove() {
95 clear();
96 }
97
98 static public void setMaxDepth(int maxDepth) {
99 }
100
101 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.slf4j.MDC;
19
20 import java.util.Stack;
21
22 /**
23 * A log4j's NDC implemented in terms of SLF4J MDC primitives.
24 *
25 * @since SLF4J 1.6.0
26 */
27
28 public class NDC {
29
30 public final static String PREFIX = "NDC";
31
32 public static void clear() {
33 int depth = getDepth();
34 for (int i = 0; i < depth; i++) {
35 String key = PREFIX + i;
36 MDC.remove(key);
37 }
38 }
39
40 @SuppressWarnings("rawtypes")
41 public static Stack cloneStack() {
42 return null;
43 }
44
45 @SuppressWarnings("rawtypes")
46 public static void inherit(Stack stack) {
47 }
48
49 static public String get() {
50 return null;
51 }
52
53 public static int getDepth() {
54 int i = 0;
55 while (true) {
56 String val = MDC.get(PREFIX + i);
57 if (val != null) {
58 i++;
59 } else {
60 break;
61 }
62 }
63 return i;
64 }
65
66 public static String pop() {
67 int next = getDepth();
68 if (next == 0) {
69 return "";
70 }
71 int last = next - 1;
72 String key = PREFIX + last;
73 String val = MDC.get(key);
74 MDC.remove(key);
75 return val;
76 }
77
78 public static String peek() {
79 int next = getDepth();
80 if (next == 0) {
81 return "";
82 }
83 int last = next - 1;
84 String key = PREFIX + last;
85 String val = MDC.get(key);
86 return val;
87 }
88
89 public static void push(String message) {
90 int next = getDepth();
91 MDC.put(PREFIX + next, message);
92 }
93
94 static public void remove() {
95 clear();
96 }
97
98 static public void setMaxDepth(int maxDepth) {
99 }
100
101 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Christian Trutz <christian.trutz@belaso.de>
17 package org.apache.log4j;
18
19 /**
20 * This class is a minimal implementation of the original Log4J class.
21 *
22 * @author Christian Trutz <christian.trutz@belaso.de>
23 * */
24 public class PatternLayout extends Layout {
25
26 public PatternLayout() {
27 super();
28 }
29
30 public PatternLayout(String pattern) {
31 super();
32 }
33
34 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Christian Trutz <christian.trutz@belaso.de>
17 package org.apache.log4j;
18
19 /**
20 * This class is a minimal implementation of the original Log4J class.
21 *
22 * @author Christian Trutz <christian.trutz@belaso.de>
23 * */
24 public class PatternLayout extends Layout {
25
26 public PatternLayout() {
27 super();
28 }
29
30 public PatternLayout(String pattern) {
31 super();
32 }
33
34 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Kitching Simon <Simon.Kitching@orange.ch>
17
18 package org.apache.log4j;
19
20 // Contributors: Kitching Simon <Simon.Kitching@OOOrange.ch>
21
22 /**
23 <font color="#AA4444">Refrain from using this class directly, use
24 the {@link Level} class instead</font>.
25
26 @author Ceki G&uuml;lc&uuml; */
27 public class Priority {
28
29 transient int level;
30 transient String levelStr;
31 transient int syslogEquivalent;
32
33 public final static int OFF_INT = Integer.MAX_VALUE;
34 public final static int FATAL_INT = 50000;
35 public final static int ERROR_INT = 40000;
36 public final static int WARN_INT = 30000;
37 public final static int INFO_INT = 20000;
38 public final static int DEBUG_INT = 10000;
39 // public final static int FINE_INT = DEBUG_INT;
40 public final static int ALL_INT = Integer.MIN_VALUE;
41
42 /**
43 * @deprecated Use {@link Level#FATAL} instead.
44 */
45 final static public Priority FATAL = new Level(FATAL_INT, "FATAL", 0);
46
47 /**
48 * @deprecated Use {@link Level#ERROR} instead.
49 */
50 final static public Priority ERROR = new Level(ERROR_INT, "ERROR", 3);
51
52 /**
53 * @deprecated Use {@link Level#WARN} instead.
54 */
55 final static public Priority WARN = new Level(WARN_INT, "WARN", 4);
56
57 /**
58 * @deprecated Use {@link Level#INFO} instead.
59 */
60 final static public Priority INFO = new Level(INFO_INT, "INFO", 6);
61
62 /**
63 * @deprecated Use {@link Level#DEBUG} instead.
64 */
65 final static public Priority DEBUG = new Level(DEBUG_INT, "DEBUG", 7);
66
67 /**
68 * Default constructor for deserialization.
69 */
70 protected Priority() {
71 level = DEBUG_INT;
72 levelStr = "DEBUG";
73 syslogEquivalent = 7;
74 }
75
76 /**
77 Instantiate a level object.
78 */
79 protected Priority(int level, String levelStr, int syslogEquivalent) {
80 this.level = level;
81 this.levelStr = levelStr;
82 this.syslogEquivalent = syslogEquivalent;
83 }
84
85 /**
86 Two priorities are equal if their level fields are equal.
87 @since 1.2
88 */
89 public boolean equals(Object o) {
90 if (o instanceof Priority) {
91 Priority r = (Priority) o;
92 return (this.level == r.level);
93 } else {
94 return false;
95 }
96 }
97
98 /**
99 Return the syslog equivalent of this priority as an integer.
100 */
101 public final int getSyslogEquivalent() {
102 return syslogEquivalent;
103 }
104
105 /**
106 Returns <code>true</code> if this level has a higher or equal
107 level than the level passed as argument, <code>false</code>
108 otherwise.
109
110 <p>You should think twice before overriding the default
111 implementation of <code>isGreaterOrEqual</code> method.
112
113 */
114 public boolean isGreaterOrEqual(Priority r) {
115 return level >= r.level;
116 }
117
118 /**
119 Return all possible priorities as an array of Level objects in
120 descending order.
121
122 @deprecated This method will be removed with no replacement.
123 */
124 public static Priority[] getAllPossiblePriorities() {
125 return new Priority[] { Priority.FATAL, Priority.ERROR, Level.WARN, Priority.INFO, Priority.DEBUG };
126 }
127
128 /**
129 Returns the string representation of this priority.
130 */
131 final public String toString() {
132 return levelStr;
133 }
134
135 /**
136 Returns the integer representation of this level.
137 */
138 public final int toInt() {
139 return level;
140 }
141
142 /**
143 * @deprecated Please use the {@link Level#toLevel(String)} method instead.
144 */
145 public static Priority toPriority(String sArg) {
146 return Level.toLevel(sArg);
147 }
148
149 /**
150 * @deprecated Please use the {@link Level#toLevel(int)} method instead.
151 */
152 public static Priority toPriority(int val) {
153 return toPriority(val, Priority.DEBUG);
154 }
155
156 /**
157 * @deprecated Please use the {@link Level#toLevel(int, Level)} method instead.
158 */
159 public static Priority toPriority(int val, Priority defaultPriority) {
160 return Level.toLevel(val, (Level) defaultPriority);
161 }
162
163 /**
164 * @deprecated Please use the {@link Level#toLevel(String, Level)} method instead.
165 */
166 public static Priority toPriority(String sArg, Priority defaultPriority) {
167 return Level.toLevel(sArg, (Level) defaultPriority);
168 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Kitching Simon <Simon.Kitching@orange.ch>
17
18 package org.apache.log4j;
19
20 // Contributors: Kitching Simon <Simon.Kitching@OOOrange.ch>
21
22 /**
23 <font color="#AA4444">Refrain from using this class directly, use
24 the {@link Level} class instead</font>.
25
26 @author Ceki G&uuml;lc&uuml; */
27 public class Priority {
28
29 transient int level;
30 transient String levelStr;
31 transient int syslogEquivalent;
32
33 public final static int OFF_INT = Integer.MAX_VALUE;
34 public final static int FATAL_INT = 50000;
35 public final static int ERROR_INT = 40000;
36 public final static int WARN_INT = 30000;
37 public final static int INFO_INT = 20000;
38 public final static int DEBUG_INT = 10000;
39 // public final static int FINE_INT = DEBUG_INT;
40 public final static int ALL_INT = Integer.MIN_VALUE;
41
42 /**
43 * @deprecated Use {@link Level#FATAL} instead.
44 */
45 final static public Priority FATAL = new Level(FATAL_INT, "FATAL", 0);
46
47 /**
48 * @deprecated Use {@link Level#ERROR} instead.
49 */
50 final static public Priority ERROR = new Level(ERROR_INT, "ERROR", 3);
51
52 /**
53 * @deprecated Use {@link Level#WARN} instead.
54 */
55 final static public Priority WARN = new Level(WARN_INT, "WARN", 4);
56
57 /**
58 * @deprecated Use {@link Level#INFO} instead.
59 */
60 final static public Priority INFO = new Level(INFO_INT, "INFO", 6);
61
62 /**
63 * @deprecated Use {@link Level#DEBUG} instead.
64 */
65 final static public Priority DEBUG = new Level(DEBUG_INT, "DEBUG", 7);
66
67 /**
68 * Default constructor for deserialization.
69 */
70 protected Priority() {
71 level = DEBUG_INT;
72 levelStr = "DEBUG";
73 syslogEquivalent = 7;
74 }
75
76 /**
77 Instantiate a level object.
78 */
79 protected Priority(int level, String levelStr, int syslogEquivalent) {
80 this.level = level;
81 this.levelStr = levelStr;
82 this.syslogEquivalent = syslogEquivalent;
83 }
84
85 /**
86 Two priorities are equal if their level fields are equal.
87 @since 1.2
88 */
89 public boolean equals(Object o) {
90 if (o instanceof Priority) {
91 Priority r = (Priority) o;
92 return (this.level == r.level);
93 } else {
94 return false;
95 }
96 }
97
98 /**
99 Return the syslog equivalent of this priority as an integer.
100 */
101 public final int getSyslogEquivalent() {
102 return syslogEquivalent;
103 }
104
105 /**
106 Returns <code>true</code> if this level has a higher or equal
107 level than the level passed as argument, <code>false</code>
108 otherwise.
109
110 <p>You should think twice before overriding the default
111 implementation of <code>isGreaterOrEqual</code> method.
112
113 */
114 public boolean isGreaterOrEqual(Priority r) {
115 return level >= r.level;
116 }
117
118 /**
119 Return all possible priorities as an array of Level objects in
120 descending order.
121
122 @deprecated This method will be removed with no replacement.
123 */
124 public static Priority[] getAllPossiblePriorities() {
125 return new Priority[] { Priority.FATAL, Priority.ERROR, Level.WARN, Priority.INFO, Priority.DEBUG };
126 }
127
128 /**
129 Returns the string representation of this priority.
130 */
131 final public String toString() {
132 return levelStr;
133 }
134
135 /**
136 Returns the integer representation of this level.
137 */
138 public final int toInt() {
139 return level;
140 }
141
142 /**
143 * @deprecated Please use the {@link Level#toLevel(String)} method instead.
144 */
145 public static Priority toPriority(String sArg) {
146 return Level.toLevel(sArg);
147 }
148
149 /**
150 * @deprecated Please use the {@link Level#toLevel(int)} method instead.
151 */
152 public static Priority toPriority(int val) {
153 return toPriority(val, Priority.DEBUG);
154 }
155
156 /**
157 * @deprecated Please use the {@link Level#toLevel(int, Level)} method instead.
158 */
159 public static Priority toPriority(int val, Priority defaultPriority) {
160 return Level.toLevel(val, (Level) defaultPriority);
161 }
162
163 /**
164 * @deprecated Please use the {@link Level#toLevel(String, Level)} method instead.
165 */
166 public static Priority toPriority(String sArg, Priority defaultPriority) {
167 return Level.toLevel(sArg, (Level) defaultPriority);
168 }
169169 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import java.net.URL;
19 import java.util.Properties;
20
21 import org.apache.log4j.spi.Configurator;
22 import org.apache.log4j.spi.LoggerRepository;
23
24 /**
25 * An nop implementation of PropertyConfigurator.
26 */
27 public class PropertyConfigurator implements Configurator {
28 public static void configure(Properties properties) {
29 }
30
31 public static void configure(String configFilename) {
32 }
33
34 public static void configure(java.net.URL configURL) {
35 }
36
37 public static void configureAndWatch(String configFilename) {
38 }
39
40 public static void configureAndWatch(String configFilename, long delay) {
41 }
42
43 public void doConfigure(Properties properties, LoggerRepository hierarchy) {
44 }
45
46 public void doConfigure(String configFileName, LoggerRepository hierarchy) {
47 }
48
49 public void doConfigure(URL configURL, LoggerRepository hierarchy) {
50 }
51 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import java.net.URL;
19 import java.util.Properties;
20
21 import org.apache.log4j.spi.Configurator;
22 import org.apache.log4j.spi.LoggerRepository;
23
24 /**
25 * An nop implementation of PropertyConfigurator.
26 */
27 public class PropertyConfigurator implements Configurator {
28 public static void configure(Properties properties) {
29 }
30
31 public static void configure(String configFilename) {
32 }
33
34 public static void configure(java.net.URL configURL) {
35 }
36
37 public static void configureAndWatch(String configFilename) {
38 }
39
40 public static void configureAndWatch(String configFilename, long delay) {
41 }
42
43 public void doConfigure(Properties properties, LoggerRepository hierarchy) {
44 }
45
46 public void doConfigure(String configFileName, LoggerRepository hierarchy) {
47 }
48
49 public void doConfigure(URL configURL, LoggerRepository hierarchy) {
50 }
51 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Christian Trutz <christian.trutz@belaso.de>
17 package org.apache.log4j;
18
19 import java.io.IOException;
20
21 /**
22 * This class is a minimal implementation of the original Log4J class.
23 *
24 * @author Christian Trutz <christian.trutz@belaso.de>
25 * */
26 public class RollingFileAppender {
27
28 public RollingFileAppender() {
29 super();
30 }
31
32 public RollingFileAppender(Layout layout, String filename) throws IOException {
33 super();
34 }
35
36 public RollingFileAppender(Layout layout, String filename, boolean append) throws IOException {
37 super();
38 }
39
40 public void setMaxBackupIndex(int maxBackups) {
41 // nothing to do
42 }
43
44 public void setMaximumFileSize(long maxFileSize) {
45 // nothing to do
46 }
47
48 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Christian Trutz <christian.trutz@belaso.de>
17 package org.apache.log4j;
18
19 import java.io.IOException;
20
21 /**
22 * This class is a minimal implementation of the original Log4J class.
23 *
24 * @author Christian Trutz <christian.trutz@belaso.de>
25 * */
26 public class RollingFileAppender {
27
28 public RollingFileAppender() {
29 super();
30 }
31
32 public RollingFileAppender(Layout layout, String filename) throws IOException {
33 super();
34 }
35
36 public RollingFileAppender(Layout layout, String filename, boolean append) throws IOException {
37 super();
38 }
39
40 public void setMaxBackupIndex(int maxBackups) {
41 // nothing to do
42 }
43
44 public void setMaximumFileSize(long maxFileSize) {
45 // nothing to do
46 }
47
48 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class SimpleLayout extends Layout {
18 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class SimpleLayout extends Layout {
18 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class WriterAppender extends AppenderSkeleton {
18
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class WriterAppender extends AppenderSkeleton {
18
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.helpers;
17
18 /**
19 This class used to output log statements from within the log4j package.
20
21 <p>Log4j components cannot make log4j logging calls. However, it is
22 sometimes useful for the user to learn about what log4j is
23 doing. You can enable log4j internal logging by defining the
24 <b>log4j.configDebug</b> variable.
25
26 <p>All log4j internal debug calls go to <code>System.out</code>
27 where as internal error messages are sent to
28 <code>System.err</code>. All internal messages are prepended with
29 the string "log4j: ".
30
31 @since 0.8.2
32 @author Ceki G&uuml;lc&uuml;
33 */
34 public class LogLog {
35
36 /**
37 Defining this value makes log4j print log4j-internal debug
38 statements to <code>System.out</code>.
39
40 <p> The value of this string is <b>log4j.debug</b>.
41
42 <p>Note that the search for all option names is case sensitive. */
43 public static final String DEBUG_KEY = "log4j.debug";
44
45 /**
46 Defining this value makes log4j components print log4j-internal
47 debug statements to <code>System.out</code>.
48
49 <p> The value of this string is <b>log4j.configDebug</b>.
50
51 <p>Note that the search for all option names is case sensitive.
52
53 @deprecated Use {@link #DEBUG_KEY} instead.
54 */
55 public static final String CONFIG_DEBUG_KEY = "log4j.configDebug";
56
57 protected static boolean debugEnabled = false;
58
59 /**
60 In quietMode not even errors generate any output.
61 */
62 private static boolean quietMode = false;
63
64 private static final String PREFIX = "log4j: ";
65 private static final String ERR_PREFIX = "log4j:ERROR ";
66 private static final String WARN_PREFIX = "log4j:WARN ";
67
68 static {
69 }
70
71 /**
72 Allows to enable/disable log4j internal logging.
73 */
74 static public void setInternalDebugging(boolean enabled) {
75 debugEnabled = enabled;
76 }
77
78 /**
79 This method is used to output log4j internal debug
80 statements. Output goes to <code>System.out</code>.
81 */
82 public static void debug(String msg) {
83 if (debugEnabled && !quietMode) {
84 System.out.println(PREFIX + msg);
85 }
86 }
87
88 /**
89 This method is used to output log4j internal debug
90 statements. Output goes to <code>System.out</code>.
91 */
92 public static void debug(String msg, Throwable t) {
93 if (debugEnabled && !quietMode) {
94 System.out.println(PREFIX + msg);
95 if (t != null)
96 t.printStackTrace(System.out);
97 }
98 }
99
100 /**
101 This method is used to output log4j internal error
102 statements. There is no way to disable error statements.
103 Output goes to <code>System.err</code>.
104 */
105 public static void error(String msg) {
106 if (quietMode)
107 return;
108 System.err.println(ERR_PREFIX + msg);
109 }
110
111 /**
112 This method is used to output log4j internal error
113 statements. There is no way to disable error statements.
114 Output goes to <code>System.err</code>.
115 */
116 public static void error(String msg, Throwable t) {
117 if (quietMode)
118 return;
119
120 System.err.println(ERR_PREFIX + msg);
121 if (t != null) {
122 t.printStackTrace();
123 }
124 }
125
126 /**
127 In quite mode no LogLog generates strictly no output, not even
128 for errors.
129
130 @param quietMode A true for not
131 */
132 public static void setQuietMode(boolean quietMode) {
133 LogLog.quietMode = quietMode;
134 }
135
136 /**
137 This method is used to output log4j internal warning
138 statements. There is no way to disable warning statements.
139 Output goes to <code>System.err</code>. */
140 public static void warn(String msg) {
141 if (quietMode)
142 return;
143
144 System.err.println(WARN_PREFIX + msg);
145 }
146
147 /**
148 This method is used to output log4j internal warnings. There is
149 no way to disable warning statements. Output goes to
150 <code>System.err</code>. */
151 public static void warn(String msg, Throwable t) {
152 if (quietMode)
153 return;
154
155 System.err.println(WARN_PREFIX + msg);
156 if (t != null) {
157 t.printStackTrace();
158 }
159 }
160 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.helpers;
17
18 /**
19 This class used to output log statements from within the log4j package.
20
21 <p>Log4j components cannot make log4j logging calls. However, it is
22 sometimes useful for the user to learn about what log4j is
23 doing. You can enable log4j internal logging by defining the
24 <b>log4j.configDebug</b> variable.
25
26 <p>All log4j internal debug calls go to <code>System.out</code>
27 where as internal error messages are sent to
28 <code>System.err</code>. All internal messages are prepended with
29 the string "log4j: ".
30
31 @since 0.8.2
32 @author Ceki G&uuml;lc&uuml;
33 */
34 public class LogLog {
35
36 /**
37 Defining this value makes log4j print log4j-internal debug
38 statements to <code>System.out</code>.
39
40 <p> The value of this string is <b>log4j.debug</b>.
41
42 <p>Note that the search for all option names is case sensitive. */
43 public static final String DEBUG_KEY = "log4j.debug";
44
45 /**
46 Defining this value makes log4j components print log4j-internal
47 debug statements to <code>System.out</code>.
48
49 <p> The value of this string is <b>log4j.configDebug</b>.
50
51 <p>Note that the search for all option names is case sensitive.
52
53 @deprecated Use {@link #DEBUG_KEY} instead.
54 */
55 public static final String CONFIG_DEBUG_KEY = "log4j.configDebug";
56
57 protected static boolean debugEnabled = false;
58
59 /**
60 In quietMode not even errors generate any output.
61 */
62 private static boolean quietMode = false;
63
64 private static final String PREFIX = "log4j: ";
65 private static final String ERR_PREFIX = "log4j:ERROR ";
66 private static final String WARN_PREFIX = "log4j:WARN ";
67
68 static {
69 }
70
71 /**
72 Allows to enable/disable log4j internal logging.
73 */
74 static public void setInternalDebugging(boolean enabled) {
75 debugEnabled = enabled;
76 }
77
78 /**
79 This method is used to output log4j internal debug
80 statements. Output goes to <code>System.out</code>.
81 */
82 public static void debug(String msg) {
83 if (debugEnabled && !quietMode) {
84 System.out.println(PREFIX + msg);
85 }
86 }
87
88 /**
89 This method is used to output log4j internal debug
90 statements. Output goes to <code>System.out</code>.
91 */
92 public static void debug(String msg, Throwable t) {
93 if (debugEnabled && !quietMode) {
94 System.out.println(PREFIX + msg);
95 if (t != null)
96 t.printStackTrace(System.out);
97 }
98 }
99
100 /**
101 This method is used to output log4j internal error
102 statements. There is no way to disable error statements.
103 Output goes to <code>System.err</code>.
104 */
105 public static void error(String msg) {
106 if (quietMode)
107 return;
108 System.err.println(ERR_PREFIX + msg);
109 }
110
111 /**
112 This method is used to output log4j internal error
113 statements. There is no way to disable error statements.
114 Output goes to <code>System.err</code>.
115 */
116 public static void error(String msg, Throwable t) {
117 if (quietMode)
118 return;
119
120 System.err.println(ERR_PREFIX + msg);
121 if (t != null) {
122 t.printStackTrace();
123 }
124 }
125
126 /**
127 In quite mode no LogLog generates strictly no output, not even
128 for errors.
129
130 @param quietMode A true for not
131 */
132 public static void setQuietMode(boolean quietMode) {
133 LogLog.quietMode = quietMode;
134 }
135
136 /**
137 This method is used to output log4j internal warning
138 statements. There is no way to disable warning statements.
139 Output goes to <code>System.err</code>. */
140 public static void warn(String msg) {
141 if (quietMode)
142 return;
143
144 System.err.println(WARN_PREFIX + msg);
145 }
146
147 /**
148 This method is used to output log4j internal warnings. There is
149 no way to disable warning statements. Output goes to
150 <code>System.err</code>. */
151 public static void warn(String msg, Throwable t) {
152 if (quietMode)
153 return;
154
155 System.err.println(WARN_PREFIX + msg);
156 if (t != null) {
157 t.printStackTrace();
158 }
159 }
160 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.log4j.helpers;
18
19 import java.util.Enumeration;
20 import java.util.NoSuchElementException;
21
22 /**
23 * An always-empty Enumerator.
24 *
25 * @author Anders Kristensen
26 * @since version 1.0
27 */
28 @SuppressWarnings("rawtypes")
29 public class NullEnumeration implements Enumeration {
30 private static final NullEnumeration instance = new NullEnumeration();
31
32 private NullEnumeration() {
33 }
34
35 public static NullEnumeration getInstance() {
36 return instance;
37 }
38
39 public boolean hasMoreElements() {
40 return false;
41 }
42
43 public Object nextElement() {
44 throw new NoSuchElementException();
45 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.log4j.helpers;
18
19 import java.util.Enumeration;
20 import java.util.NoSuchElementException;
21
22 /**
23 * An always-empty Enumerator.
24 *
25 * @author Anders Kristensen
26 * @since version 1.0
27 */
28 @SuppressWarnings("rawtypes")
29 public class NullEnumeration implements Enumeration {
30 private static final NullEnumeration instance = new NullEnumeration();
31
32 private NullEnumeration() {
33 }
34
35 public static NullEnumeration getInstance() {
36 return instance;
37 }
38
39 public boolean hasMoreElements() {
40 return false;
41 }
42
43 public Object nextElement() {
44 throw new NoSuchElementException();
45 }
4646 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>An rather minimal but sufficient implementation redirecting all
12 calls to a log4j logger to a logback logger.</p>
13
14 </body>
15 </html>
16
17
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>An rather minimal but sufficient implementation redirecting all
12 calls to a log4j logger to a logback logger.</p>
13
14 </body>
15 </html>
16
17
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.spi.LoggerRepository;
19 import java.net.URL;
20
21 /**
22 Implemented by classes capable of configuring log4j using a URL.
23
24 @since 1.0
25 @author Anders Kristensen
26 */
27 public interface Configurator {
28
29 /**
30 Special level value signifying inherited behaviour. The current
31 value of this string constant is <b>inherited</b>. {@link #NULL}
32 is a synonym. */
33 public static final String INHERITED = "inherited";
34
35 /**
36 Special level signifying inherited behaviour, same as {@link
37 #INHERITED}. The current value of this string constant is
38 <b>null</b>. */
39 public static final String NULL = "null";
40
41 /**
42 Interpret a resource pointed by a URL and set up log4j accordingly.
43
44 The configuration is done relative to the <code>hierarchy</code>
45 parameter.
46
47 @param url The URL to parse
48 @param repository The hierarchy to operation upon.
49 */
50 void doConfigure(URL url, LoggerRepository repository);
51 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.spi.LoggerRepository;
19 import java.net.URL;
20
21 /**
22 Implemented by classes capable of configuring log4j using a URL.
23
24 @since 1.0
25 @author Anders Kristensen
26 */
27 public interface Configurator {
28
29 /**
30 Special level value signifying inherited behaviour. The current
31 value of this string constant is <b>inherited</b>. {@link #NULL}
32 is a synonym. */
33 public static final String INHERITED = "inherited";
34
35 /**
36 Special level signifying inherited behaviour, same as {@link
37 #INHERITED}. The current value of this string constant is
38 <b>null</b>. */
39 public static final String NULL = "null";
40
41 /**
42 Interpret a resource pointed by a URL and set up log4j accordingly.
43
44 The configuration is done relative to the <code>hierarchy</code>
45 parameter.
46
47 @param url The URL to parse
48 @param repository The hierarchy to operation upon.
49 */
50 void doConfigure(URL url, LoggerRepository repository);
51 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 /**
19 * Created by IntelliJ IDEA.
20 * User: ceki
21 * Date: 19 oct. 2010
22 * Time: 11:46:24
23 * To change this template use File | Settings | File Templates.
24 */
25 public class ErrorHandler {
26 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 /**
19 * Created by IntelliJ IDEA.
20 * User: ceki
21 * Date: 19 oct. 2010
22 * Time: 11:46:24
23 * To change this template use File | Settings | File Templates.
24 */
25 public class ErrorHandler {
26 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 public class Filter {
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 public class Filter {
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.*;
19
20 /**
21 Listen to events occurring within a {@link
22 org.apache.log4j.Hierarchy Hierarchy}.
23
24 @author Ceki G&uuml;lc&uuml;
25 @since 1.2
26
27 */
28 public interface HierarchyEventListener {
29
30 // public
31 // void categoryCreationEvent(Category cat);
32
33 public void addAppenderEvent(Category cat, Appender appender);
34
35 public void removeAppenderEvent(Category cat, Appender appender);
36
37 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.*;
19
20 /**
21 Listen to events occurring within a {@link
22 org.apache.log4j.Hierarchy Hierarchy}.
23
24 @author Ceki G&uuml;lc&uuml;
25 @since 1.2
26
27 */
28 public interface HierarchyEventListener {
29
30 // public
31 // void categoryCreationEvent(Category cat);
32
33 public void addAppenderEvent(Category cat, Appender appender);
34
35 public void removeAppenderEvent(Category cat, Appender appender);
36
37 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.Logger;
19
20 /**
21
22 Implement this interface to create new instances of Logger or
23 a sub-class of Logger.
24
25 <p>See <code>examples/subclass/MyLogger.java</code> for an example.
26
27 @author Ceki G&uuml;lc&uuml;
28 @since version 0.8.5
29
30 */
31 public interface LoggerFactory {
32
33 public Logger makeNewLoggerInstance(String name);
34
35 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.Logger;
19
20 /**
21
22 Implement this interface to create new instances of Logger or
23 a sub-class of Logger.
24
25 <p>See <code>examples/subclass/MyLogger.java</code> for an example.
26
27 @author Ceki G&uuml;lc&uuml;
28 @since version 0.8.5
29
30 */
31 public interface LoggerFactory {
32
33 public Logger makeNewLoggerInstance(String name);
34
35 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.*;
19
20 import java.util.Enumeration;
21
22 /**
23 * A <code>LoggerRepository</code> is used to create and retrieve
24 * <code>Loggers</code>. The relation between loggers in a repository
25 * depends on the repository but typically loggers are arranged in a
26 * named hierarchy.
27 * <p/>
28 * <p>In addition to the creational methods, a
29 * <code>LoggerRepository</code> can be queried for existing loggers,
30 * can act as a point of registry for events related to loggers.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 * @since 1.2
34 */
35 public interface LoggerRepository {
36
37 /**
38 * Add a {@link HierarchyEventListener} event to the repository.
39 */
40 public void addHierarchyEventListener(HierarchyEventListener listener);
41
42 /**
43 * Returns whether this repository is disabled for a given
44 * level. The answer depends on the repository threshold and the
45 * <code>level</code> parameter. See also {@link #setThreshold}
46 * method.
47 */
48 boolean isDisabled(int level);
49
50 /**
51 * Set the repository-wide threshold. All logging requests below the
52 * threshold are immediately dropped. By default, the threshold is
53 * set to <code>Level.ALL</code> which has the lowest possible rank.
54 */
55 public void setThreshold(Level level);
56
57 /**
58 * Another form of {@link #setThreshold(Level)} accepting a string
59 * parameter instead of a <code>Level</code>.
60 */
61 public void setThreshold(String val);
62
63 public void emitNoAppenderWarning(Category cat);
64
65 /**
66 * Get the repository-wide threshold. See {@link
67 * #setThreshold(Level)} for an explanation.
68 */
69 public Level getThreshold();
70
71 public Logger getLogger(String name);
72
73 public Logger getLogger(String name, LoggerFactory factory);
74
75 public Logger getRootLogger();
76
77 public abstract Logger exists(String name);
78
79 public abstract void shutdown();
80
81 @SuppressWarnings("rawtypes")
82 public Enumeration getCurrentLoggers();
83
84 /**
85 * Deprecated. Please use {@link #getCurrentLoggers} instead.
86 */
87 @SuppressWarnings("rawtypes")
88 public Enumeration getCurrentCategories();
89
90 public abstract void fireAddAppenderEvent(Category logger, Appender appender);
91
92 public abstract void resetConfiguration();
93
94 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.*;
19
20 import java.util.Enumeration;
21
22 /**
23 * A <code>LoggerRepository</code> is used to create and retrieve
24 * <code>Loggers</code>. The relation between loggers in a repository
25 * depends on the repository but typically loggers are arranged in a
26 * named hierarchy.
27 * <p/>
28 * <p>In addition to the creational methods, a
29 * <code>LoggerRepository</code> can be queried for existing loggers,
30 * can act as a point of registry for events related to loggers.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 * @since 1.2
34 */
35 public interface LoggerRepository {
36
37 /**
38 * Add a {@link HierarchyEventListener} event to the repository.
39 */
40 public void addHierarchyEventListener(HierarchyEventListener listener);
41
42 /**
43 * Returns whether this repository is disabled for a given
44 * level. The answer depends on the repository threshold and the
45 * <code>level</code> parameter. See also {@link #setThreshold}
46 * method.
47 */
48 boolean isDisabled(int level);
49
50 /**
51 * Set the repository-wide threshold. All logging requests below the
52 * threshold are immediately dropped. By default, the threshold is
53 * set to <code>Level.ALL</code> which has the lowest possible rank.
54 */
55 public void setThreshold(Level level);
56
57 /**
58 * Another form of {@link #setThreshold(Level)} accepting a string
59 * parameter instead of a <code>Level</code>.
60 */
61 public void setThreshold(String val);
62
63 public void emitNoAppenderWarning(Category cat);
64
65 /**
66 * Get the repository-wide threshold. See {@link
67 * #setThreshold(Level)} for an explanation.
68 */
69 public Level getThreshold();
70
71 public Logger getLogger(String name);
72
73 public Logger getLogger(String name, LoggerFactory factory);
74
75 public Logger getRootLogger();
76
77 public abstract Logger exists(String name);
78
79 public abstract void shutdown();
80
81 @SuppressWarnings("rawtypes")
82 public Enumeration getCurrentLoggers();
83
84 /**
85 * Deprecated. Please use {@link #getCurrentLoggers} instead.
86 */
87 @SuppressWarnings("rawtypes")
88 public Enumeration getCurrentCategories();
89
90 public abstract void fireAddAppenderEvent(Category logger, Appender appender);
91
92 public abstract void resetConfiguration();
93
94 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 public class LoggingEvent {
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 public class LoggingEvent {
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j.spi;
16
17 public interface OptionHandler {
18
19 void activateOptions();
20
21 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j.spi;
16
17 public interface OptionHandler {
18
19 void activateOptions();
20
21 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.xml;
17
18 import org.apache.log4j.spi.Configurator;
19 import org.apache.log4j.spi.LoggerRepository;
20
21 import javax.xml.parsers.FactoryConfigurationError;
22 import java.io.InputStream;
23 import java.io.Reader;
24 import java.net.URL;
25 import java.util.Properties;
26
27 import org.w3c.dom.Element;
28
29 public class DOMConfigurator implements Configurator {
30
31 public static void configure(Element element) {
32 }
33
34 public static void configure(String filename) throws FactoryConfigurationError {
35 }
36
37 static public void configure(URL url) throws FactoryConfigurationError {
38 }
39
40 static public void configureAndWatch(String configFilename) {
41 }
42
43 public static void configureAndWatch(String configFilename, long delay) {
44 }
45
46 public void doConfigure(Element element, LoggerRepository repository) {
47 }
48
49 public void doConfigure(InputStream inputStream, LoggerRepository repository) throws FactoryConfigurationError {
50 }
51
52 public void doConfigure(Reader reader, LoggerRepository repository) throws FactoryConfigurationError {
53 }
54
55 public void doConfigure(String filename, LoggerRepository repository) {
56 }
57
58 public void doConfigure(URL url, LoggerRepository repository) {
59 }
60
61 public static String subst(String value, Properties props) {
62 return value;
63 }
64
65 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.xml;
17
18 import org.apache.log4j.spi.Configurator;
19 import org.apache.log4j.spi.LoggerRepository;
20
21 import javax.xml.parsers.FactoryConfigurationError;
22 import java.io.InputStream;
23 import java.io.Reader;
24 import java.net.URL;
25 import java.util.Properties;
26
27 import org.w3c.dom.Element;
28
29 public class DOMConfigurator implements Configurator {
30
31 public static void configure(Element element) {
32 }
33
34 public static void configure(String filename) throws FactoryConfigurationError {
35 }
36
37 static public void configure(URL url) throws FactoryConfigurationError {
38 }
39
40 static public void configureAndWatch(String configFilename) {
41 }
42
43 public static void configureAndWatch(String configFilename, long delay) {
44 }
45
46 public void doConfigure(Element element, LoggerRepository repository) {
47 }
48
49 public void doConfigure(InputStream inputStream, LoggerRepository repository) throws FactoryConfigurationError {
50 }
51
52 public void doConfigure(Reader reader, LoggerRepository repository) throws FactoryConfigurationError {
53 }
54
55 public void doConfigure(String filename, LoggerRepository repository) {
56 }
57
58 public void doConfigure(URL url, LoggerRepository repository) {
59 }
60
61 public static String subst(String value, Properties props) {
62 return value;
63 }
64
65 }
0 Implementation-Title: log4j-over-slf4j
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: log4j.over.slf4j
3 Bundle-Name: log4j-over-slf4j
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.apache.log4j;version=${log4j.version},
7 org.apache.log4j.helpers;version=${log4j.version},
8 org.apache.log4j.spi;version=${log4j.version},
9 org.apache.log4j.xml;version=${log4j.version}
10 Import-Package: org.slf4j;version=${slf4j.api.minimum.compatible.version},
11 org.slf4j.helpers;version=${slf4j.api.minimum.compatible.version},
12 org.slf4j.spi;version=${slf4j.api.minimum.compatible.version}
0 Implementation-Title: log4j-over-slf4j
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: log4j.over.slf4j
3 Bundle-Name: log4j-over-slf4j
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.apache.log4j;version=${log4j.version},
7 org.apache.log4j.helpers;version=${log4j.version},
8 org.apache.log4j.spi;version=${log4j.version},
9 org.apache.log4j.xml;version=${log4j.version}
10 Import-Package: org.slf4j;version=${slf4j.api.minimum.compatible.version},
11 org.slf4j.helpers;version=${slf4j.api.minimum.compatible.version},
12 org.slf4j.spi;version=${slf4j.api.minimum.compatible.version}
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.apache.log4j;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.After;
29 import org.junit.Before;
30 import org.junit.Test;
31
32 /**
33 * @author Ceki G&uuml;lc&uuml;
34 */
35 public class NDCTest {
36
37 @Before
38 public void setUp() {
39 assertEquals(0, NDC.getDepth());
40 }
41
42 @After
43 public void tearDown() {
44 NDC.clear();
45 }
46
47 @Test
48 public void testSmoke() {
49 NDC.push("a");
50 String back = NDC.pop();
51 assertEquals("a", back);
52 }
53
54 @Test
55 public void testPop() {
56 NDC.push("peek");
57 String back = NDC.peek();
58 assertEquals("peek", back);
59 }
60
61 @Test
62 public void testClear() {
63 NDC.push("clear");
64 NDC.clear();
65 assertEquals(0, NDC.getDepth());
66 }
67
68 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.apache.log4j;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.After;
29 import org.junit.Before;
30 import org.junit.Test;
31
32 /**
33 * @author Ceki G&uuml;lc&uuml;
34 */
35 public class NDCTest {
36
37 @Before
38 public void setUp() {
39 assertEquals(0, NDC.getDepth());
40 }
41
42 @After
43 public void tearDown() {
44 NDC.clear();
45 }
46
47 @Test
48 public void testSmoke() {
49 NDC.push("a");
50 String back = NDC.pop();
51 assertEquals("a", back);
52 }
53
54 @Test
55 public void testPop() {
56 NDC.push("peek");
57 String back = NDC.peek();
58 assertEquals("peek", back);
59 }
60
61 @Test
62 public void testClear() {
63 NDC.push("clear");
64 NDC.clear();
65 assertEquals(0, NDC.getDepth());
66 }
67
68 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.apache.log4j;
25
26 import org.apache.log4j.Logger;
27
28 import junit.framework.TestCase;
29
30 public class Trivial extends TestCase {
31
32 public void testSmoke() {
33 Logger l = Logger.getLogger("a");
34 l.trace("t");
35 l.debug("d");
36 l.info("i");
37 l.warn("w");
38 l.error("e");
39 l.fatal("f");
40
41 Exception e = new Exception("testing");
42 l.trace("t", e);
43 l.debug("d", e);
44 l.info("i", e);
45 l.warn("w", e);
46 l.error("e", e);
47 l.fatal("f", e);
48 }
49
50 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.apache.log4j;
25
26 import org.apache.log4j.Logger;
27
28 import junit.framework.TestCase;
29
30 public class Trivial extends TestCase {
31
32 public void testSmoke() {
33 Logger l = Logger.getLogger("a");
34 l.trace("t");
35 l.debug("d");
36 l.info("i");
37 l.warn("w");
38 l.error("e");
39 l.fatal("f");
40
41 Exception e = new Exception("testing");
42 l.trace("t", e);
43 l.debug("d", e);
44 l.info("i", e);
45 l.warn("w", e);
46 l.error("e", e);
47 l.fatal("f", e);
48 }
49
50 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.dummy;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.util.logging.Level;
29 import java.util.logging.LogRecord;
30
31 import org.apache.log4j.Category;
32 import org.apache.log4j.Logger;
33 import org.junit.Test;
34
35 public class Bug131 {
36
37 @Test
38 public void testBug131() {
39
40 ListHandler listHandler = new ListHandler();
41 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
42 root.addHandler(listHandler);
43 root.setLevel(Level.FINEST);
44 Logger log4jLogger = Logger.getLogger("a");
45 Category log4jCategory = Logger.getLogger("b");
46
47 int n = 0;
48
49 log4jLogger.trace("msg" + (n++));
50 log4jLogger.debug("msg" + (n++));
51 log4jLogger.info("msg" + (n++));
52 log4jLogger.warn("msg" + (n++));
53 log4jLogger.error("msg" + (n++));
54 log4jLogger.fatal("msg" + (n++));
55
56 log4jCategory.debug("msg" + (n++));
57 log4jCategory.info("msg" + (n++));
58 log4jCategory.warn("msg" + (n++));
59 log4jCategory.error("msg" + (n++));
60 log4jCategory.fatal("msg" + (n++));
61
62 assertEquals(n, listHandler.list.size());
63
64 for (int i = 0; i < n; i++) {
65 LogRecord logRecord = (LogRecord) listHandler.list.get(i);
66 assertEquals("testBug131", logRecord.getSourceMethodName());
67 }
68 }
69 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.dummy;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.util.logging.Level;
29 import java.util.logging.LogRecord;
30
31 import org.apache.log4j.Category;
32 import org.apache.log4j.Logger;
33 import org.junit.Test;
34
35 public class Bug131 {
36
37 @Test
38 public void testBug131() {
39
40 ListHandler listHandler = new ListHandler();
41 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
42 root.addHandler(listHandler);
43 root.setLevel(Level.FINEST);
44 Logger log4jLogger = Logger.getLogger("a");
45 Category log4jCategory = Logger.getLogger("b");
46
47 int n = 0;
48
49 log4jLogger.trace("msg" + (n++));
50 log4jLogger.debug("msg" + (n++));
51 log4jLogger.info("msg" + (n++));
52 log4jLogger.warn("msg" + (n++));
53 log4jLogger.error("msg" + (n++));
54 log4jLogger.fatal("msg" + (n++));
55
56 log4jCategory.debug("msg" + (n++));
57 log4jCategory.info("msg" + (n++));
58 log4jCategory.warn("msg" + (n++));
59 log4jCategory.error("msg" + (n++));
60 log4jCategory.fatal("msg" + (n++));
61
62 assertEquals(n, listHandler.list.size());
63
64 for (int i = 0; i < n; i++) {
65 LogRecord logRecord = (LogRecord) listHandler.list.get(i);
66 assertEquals("testBug131", logRecord.getSourceMethodName());
67 }
68 }
69 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.dummy;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.util.logging.Level;
29 import java.util.logging.LogRecord;
30
31 import org.apache.log4j.Category;
32 import org.apache.log4j.Logger;
33 import org.junit.Test;
34
35 public class Bug139 {
36
37 @Test
38 public void test() {
39 ListHandler listHandler = new ListHandler();
40 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
41 root.addHandler(listHandler);
42 root.setLevel(Level.FINEST);
43 Logger log4jLogger = Logger.getLogger("a");
44 Category log4jCategory = Logger.getLogger("b");
45
46 int n = 0;
47
48 log4jLogger.log(org.apache.log4j.Level.DEBUG, "hello" + (++n));
49 log4jCategory.log(org.apache.log4j.Level.DEBUG, "world" + (++n));
50
51 assertEquals(n, listHandler.list.size());
52
53 for (int i = 0; i < n; i++) {
54 LogRecord logRecord = (LogRecord) listHandler.list.get(i);
55 assertEquals("test", logRecord.getSourceMethodName());
56 }
57 }
58 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.dummy;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.util.logging.Level;
29 import java.util.logging.LogRecord;
30
31 import org.apache.log4j.Category;
32 import org.apache.log4j.Logger;
33 import org.junit.Test;
34
35 public class Bug139 {
36
37 @Test
38 public void test() {
39 ListHandler listHandler = new ListHandler();
40 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
41 root.addHandler(listHandler);
42 root.setLevel(Level.FINEST);
43 Logger log4jLogger = Logger.getLogger("a");
44 Category log4jCategory = Logger.getLogger("b");
45
46 int n = 0;
47
48 log4jLogger.log(org.apache.log4j.Level.DEBUG, "hello" + (++n));
49 log4jCategory.log(org.apache.log4j.Level.DEBUG, "world" + (++n));
50
51 assertEquals(n, listHandler.list.size());
52
53 for (int i = 0; i < n; i++) {
54 LogRecord logRecord = (LogRecord) listHandler.list.get(i);
55 assertEquals("test", logRecord.getSourceMethodName());
56 }
57 }
58 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.dummy;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.logging.Handler;
29 import java.util.logging.LogRecord;
30
31 public class ListHandler extends Handler {
32
33 List<LogRecord> list = new ArrayList<LogRecord>();
34
35 public void close() throws SecurityException {
36
37 }
38
39 public void flush() {
40
41 }
42
43 public void publish(LogRecord logRecord) {
44 logRecord.getSourceClassName();
45 list.add(logRecord);
46 }
47
48 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.dummy;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.logging.Handler;
29 import java.util.logging.LogRecord;
30
31 public class ListHandler extends Handler {
32
33 List<LogRecord> list = new ArrayList<LogRecord>();
34
35 public void close() throws SecurityException {
36
37 }
38
39 public void flush() {
40
41 }
42
43 public void publish(LogRecord logRecord) {
44 logRecord.getSourceClassName();
45 list.add(logRecord);
46 }
47
48 }
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>osgi-over-slf4j</artifactId>
13
14 <packaging>jar</packaging>
15 <name>OSGi LogService implemented over SLF4J</name>
16
17 <url>http://www.slf4j.org</url>
18 <description>
19 OSGi LogService implementation over SLF4J
20 </description>
21
22 <dependencies>
23 <dependency>
24 <groupId>org.osgi</groupId>
25 <artifactId>org.osgi.core</artifactId>
26 <version>4.2.0</version>
27 <scope>provided</scope>
28 </dependency>
29 <dependency>
30 <groupId>org.osgi</groupId>
31 <artifactId>org.osgi.enterprise</artifactId>
32 <version>4.2.0</version>
33 <scope>provided</scope>
34 </dependency>
35
36 <dependency>
37 <groupId>org.slf4j</groupId>
38 <artifactId>slf4j-simple</artifactId>
39 <version>${project.version}</version>
40 <scope>provided</scope>
41 </dependency>
42 </dependencies>
43 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>osgi-over-slf4j</artifactId>
13
14 <packaging>jar</packaging>
15 <name>OSGi LogService implemented over SLF4J</name>
16
17 <url>http://www.slf4j.org</url>
18 <description>
19 OSGi LogService implementation over SLF4J
20 </description>
21
22 <dependencies>
23 <dependency>
24 <groupId>org.osgi</groupId>
25 <artifactId>org.osgi.core</artifactId>
26 <version>4.2.0</version>
27 <scope>provided</scope>
28 </dependency>
29 <dependency>
30 <groupId>org.osgi</groupId>
31 <artifactId>org.osgi.enterprise</artifactId>
32 <version>4.2.0</version>
33 <scope>provided</scope>
34 </dependency>
35
36 <dependency>
37 <groupId>org.slf4j</groupId>
38 <artifactId>slf4j-simple</artifactId>
39 <version>${project.version}</version>
40 <scope>provided</scope>
41 </dependency>
42 </dependencies>
43
44
45 </project>
0 /*
1 * Copyright (c) 2004-2005 QOS.ch
2 *
3 * All rights reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, and/or sell copies of the Software, and to permit persons
10 * to whom the Software is furnished to do so, provided that the above
11 * copyright notice(s) and this permission notice appear in all copies of
12 * the Software and that both the above copyright notice(s) and this
13 * permission notice appear in supporting documentation.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
18 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
20 * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
21 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
22 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
23 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 *
25 * Except as contained in this notice, the name of a copyright holder
26 * shall not be used in advertising or otherwise to promote the sale, use
27 * or other dealings in this Software without prior written authorization
28 * of the copyright holder.
29 *
30 */
31
32 package org.slf4j.osgi.logservice.impl;
33
34 import java.util.Properties;
35
36 import org.osgi.framework.BundleActivator;
37 import org.osgi.framework.BundleContext;
38 import org.osgi.framework.ServiceFactory;
39 import org.osgi.service.log.LogService;
40
41 /**
42 * <code>Activator</code> implements a simple bundle that registers a
43 * {@link LogServiceFactory} for the creation of {@link LogService} implementations.
44 *
45 * @author John Conlon
46 * @author Matt Bishop
47 **/
48 public class Activator implements BundleActivator {
49 /**
50 *
51 * Implements <code>BundleActivator.start()</code> to register a
52 * LogServiceFactory.
53 *
54 * @param bundleContext the framework context for the bundle
55 * @throws Exception
56 */
57 public void start(BundleContext bundleContext) throws Exception {
58
59 Properties props = new Properties();
60 props.put("description", "An SLF4J LogService implementation.");
61 ServiceFactory factory = new LogServiceFactory();
62 bundleContext.registerService(LogService.class.getName(), factory, props);
63 }
64
65 /**
66 *
67 * Implements <code>BundleActivator.stop()</code>.
68 *
69 * @param bundleContext the framework context for the bundle
70 * @throws Exception
71 */
72 public void stop(BundleContext bundleContext) throws Exception {
73
74 // Note: It is not required that we remove the service here, since
75 // the framework will do it automatically.
76 }
77 }
0 /*
1 * Copyright (c) 2004-2005 QOS.ch
2 *
3 * All rights reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, and/or sell copies of the Software, and to permit persons
10 * to whom the Software is furnished to do so, provided that the above
11 * copyright notice(s) and this permission notice appear in all copies of
12 * the Software and that both the above copyright notice(s) and this
13 * permission notice appear in supporting documentation.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
18 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
20 * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
21 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
22 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
23 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 *
25 * Except as contained in this notice, the name of a copyright holder
26 * shall not be used in advertising or otherwise to promote the sale, use
27 * or other dealings in this Software without prior written authorization
28 * of the copyright holder.
29 *
30 */
31
32 package org.slf4j.osgi.logservice.impl;
33
34 import java.util.Properties;
35
36 import org.osgi.framework.BundleActivator;
37 import org.osgi.framework.BundleContext;
38 import org.osgi.framework.ServiceFactory;
39 import org.osgi.service.log.LogService;
40
41 /**
42 * <code>Activator</code> implements a simple bundle that registers a
43 * {@link LogServiceFactory} for the creation of {@link LogService} implementations.
44 *
45 * @author John Conlon
46 * @author Matt Bishop
47 **/
48 public class Activator implements BundleActivator {
49 /**
50 *
51 * Implements <code>BundleActivator.start()</code> to register a
52 * LogServiceFactory.
53 *
54 * @param bundleContext the framework context for the bundle
55 * @throws Exception
56 */
57 public void start(BundleContext bundleContext) throws Exception {
58
59 Properties props = new Properties();
60 props.put("description", "An SLF4J LogService implementation.");
61 ServiceFactory factory = new LogServiceFactory();
62 bundleContext.registerService(LogService.class.getName(), factory, props);
63 }
64
65 /**
66 *
67 * Implements <code>BundleActivator.stop()</code>.
68 *
69 * @param bundleContext the framework context for the bundle
70 * @throws Exception
71 */
72 public void stop(BundleContext bundleContext) throws Exception {
73
74 // Note: It is not required that we remove the service here, since
75 // the framework will do it automatically.
76 }
77 }
0 /*
1 * Copyright (c) 2004-2005 QOS.ch
2 *
3 * All rights reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, and/or sell copies of the Software, and to permit persons
10 * to whom the Software is furnished to do so, provided that the above
11 * copyright notice(s) and this permission notice appear in all copies of
12 * the Software and that both the above copyright notice(s) and this
13 * permission notice appear in supporting documentation.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
18 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
20 * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
21 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
22 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
23 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 *
25 * Except as contained in this notice, the name of a copyright holder
26 * shall not be used in advertising or otherwise to promote the sale, use
27 * or other dealings in this Software without prior written authorization
28 * of the copyright holder.
29 *
30 */
31
32 package org.slf4j.osgi.logservice.impl;
33
34 import org.osgi.framework.Bundle;
35 import org.osgi.framework.ServiceFactory;
36 import org.osgi.framework.ServiceRegistration;
37
38 /**
39 * <code>LogServiceFactory</code> creates LogService implementations.
40 *
41 * @author John Conlon
42 * @version $Rev$, $Date$
43 */
44 public class LogServiceFactory implements ServiceFactory {
45 /*
46 * (non-Javadoc)
47 *
48 * @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle,
49 * org.osgi.framework.ServiceRegistration)
50 */
51 public Object getService(Bundle bundle, ServiceRegistration arg1) {
52 return new LogServiceImpl(bundle);
53 }
54
55 /*
56 * (non-Javadoc)
57 *
58 * @see org.osgi.framework.ServiceFactory#ungetService(org.osgi.framework.Bundle,
59 * org.osgi.framework.ServiceRegistration, java.lang.Object)
60 */
61 public void ungetService(Bundle bundle, ServiceRegistration arg1, Object arg2) {
62 // nothing to do.
63 }
64 }
0 /*
1 * Copyright (c) 2004-2005 QOS.ch
2 *
3 * All rights reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, and/or sell copies of the Software, and to permit persons
10 * to whom the Software is furnished to do so, provided that the above
11 * copyright notice(s) and this permission notice appear in all copies of
12 * the Software and that both the above copyright notice(s) and this
13 * permission notice appear in supporting documentation.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
18 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
20 * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
21 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
22 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
23 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 *
25 * Except as contained in this notice, the name of a copyright holder
26 * shall not be used in advertising or otherwise to promote the sale, use
27 * or other dealings in this Software without prior written authorization
28 * of the copyright holder.
29 *
30 */
31
32 package org.slf4j.osgi.logservice.impl;
33
34 import org.osgi.framework.Bundle;
35 import org.osgi.framework.ServiceFactory;
36 import org.osgi.framework.ServiceRegistration;
37
38 /**
39 * <code>LogServiceFactory</code> creates LogService implementations.
40 *
41 * @author John Conlon
42 * @version $Rev$, $Date$
43 */
44 public class LogServiceFactory implements ServiceFactory {
45 /*
46 * (non-Javadoc)
47 *
48 * @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle,
49 * org.osgi.framework.ServiceRegistration)
50 */
51 public Object getService(Bundle bundle, ServiceRegistration arg1) {
52 return new LogServiceImpl(bundle);
53 }
54
55 /*
56 * (non-Javadoc)
57 *
58 * @see org.osgi.framework.ServiceFactory#ungetService(org.osgi.framework.Bundle,
59 * org.osgi.framework.ServiceRegistration, java.lang.Object)
60 */
61 public void ungetService(Bundle bundle, ServiceRegistration arg1, Object arg2) {
62 // nothing to do.
63 }
64 }
0 /*
1 * Copyright (c) 2004-2005 QOS.ch
2 *
3 * All rights reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, and/or sell copies of the Software, and to permit persons
10 * to whom the Software is furnished to do so, provided that the above
11 * copyright notice(s) and this permission notice appear in all copies of
12 * the Software and that both the above copyright notice(s) and this
13 * permission notice appear in supporting documentation.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
18 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
20 * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
21 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
22 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
23 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 *
25 * Except as contained in this notice, the name of a copyright holder
26 * shall not be used in advertising or otherwise to promote the sale, use
27 * or other dealings in this Software without prior written authorization
28 * of the copyright holder.
29 *
30 */
31
32 package org.slf4j.osgi.logservice.impl;
33
34 import org.osgi.framework.Bundle;
35 import org.osgi.framework.ServiceReference;
36 import org.osgi.framework.Version;
37 import org.osgi.service.log.LogService;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42 * <code>LogServiceImpl</code> is a simple OSGi LogService implementation that delegates to a slf4j
43 * Logger.
44 *
45 * @author John Conlon
46 * @author Matt Bishop
47 */
48 public class LogServiceImpl implements LogService {
49
50 private static final String UNKNOWN = "[Unknown]";
51
52 private final Logger delegate;
53
54 /**
55 * Creates a new instance of LogServiceImpl.
56 *
57 * @param bundle The bundle to create a new LogService for.
58 */
59 public LogServiceImpl(Bundle bundle) {
60
61 String name = bundle.getSymbolicName();
62 Version version = bundle.getVersion();
63 if (version == null) {
64 version = Version.emptyVersion;
65 }
66 delegate = LoggerFactory.getLogger(name + '.' + version);
67 }
68
69 /*
70 * (non-Javadoc)
71 *
72 * @see org.osgi.service.log.LogService#log(int, java.lang.String)
73 */
74 public void log(int level, String message) {
75
76 switch (level) {
77 case LOG_DEBUG:
78 delegate.debug(message);
79 break;
80 case LOG_ERROR:
81 delegate.error(message);
82 break;
83 case LOG_INFO:
84 delegate.info(message);
85 break;
86 case LOG_WARNING:
87 delegate.warn(message);
88 break;
89 default:
90 break;
91 }
92 }
93
94 /*
95 * (non-Javadoc)
96 *
97 * @see org.osgi.service.log.LogService#log(int, java.lang.String, java.lang.Throwable)
98 */
99 public void log(int level, String message, Throwable exception) {
100
101 switch (level) {
102 case LOG_DEBUG:
103 delegate.debug(message, exception);
104 break;
105 case LOG_ERROR:
106 delegate.error(message, exception);
107 break;
108 case LOG_INFO:
109 delegate.info(message, exception);
110 break;
111 case LOG_WARNING:
112 delegate.warn(message, exception);
113 break;
114 default:
115 break;
116 }
117 }
118
119 /*
120 * (non-Javadoc)
121 *
122 * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String)
123 */
124 public void log(ServiceReference sr, int level, String message) {
125
126 switch (level) {
127 case LOG_DEBUG:
128 if (delegate.isDebugEnabled()) {
129 delegate.debug(createMessage(sr, message));
130 }
131 break;
132 case LOG_ERROR:
133 if (delegate.isErrorEnabled()) {
134 delegate.error(createMessage(sr, message));
135 }
136 break;
137 case LOG_INFO:
138 if (delegate.isInfoEnabled()) {
139 delegate.info(createMessage(sr, message));
140 }
141 break;
142 case LOG_WARNING:
143 if (delegate.isWarnEnabled()) {
144 delegate.warn(createMessage(sr, message));
145 }
146 break;
147 default:
148 break;
149 }
150 }
151
152 /**
153 * Formats the log message to indicate the service sending it, if known.
154 *
155 * @param sr the ServiceReference sending the message.
156 * @param message The message to log.
157 * @return The formatted log message.
158 */
159 private String createMessage(ServiceReference sr, String message) {
160
161 StringBuilder output = new StringBuilder();
162 if (sr != null) {
163 output.append('[').append(sr.toString()).append(']');
164 } else {
165 output.append(UNKNOWN);
166 }
167 output.append(message);
168
169 return output.toString();
170 }
171
172 /*
173 * (non-Javadoc)
174 *
175 * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String,
176 * java.lang.Throwable)
177 */
178 public void log(ServiceReference sr, int level, String message, Throwable exception) {
179
180 switch (level) {
181 case LOG_DEBUG:
182 if (delegate.isDebugEnabled()) {
183 delegate.debug(createMessage(sr, message), exception);
184 }
185 break;
186 case LOG_ERROR:
187 if (delegate.isErrorEnabled()) {
188 delegate.error(createMessage(sr, message), exception);
189 }
190 break;
191 case LOG_INFO:
192 if (delegate.isInfoEnabled()) {
193 delegate.info(createMessage(sr, message), exception);
194 }
195 break;
196 case LOG_WARNING:
197 if (delegate.isWarnEnabled()) {
198 delegate.warn(createMessage(sr, message), exception);
199 }
200 break;
201 default:
202 break;
203 }
204 }
205 }
0 /*
1 * Copyright (c) 2004-2005 QOS.ch
2 *
3 * All rights reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, and/or sell copies of the Software, and to permit persons
10 * to whom the Software is furnished to do so, provided that the above
11 * copyright notice(s) and this permission notice appear in all copies of
12 * the Software and that both the above copyright notice(s) and this
13 * permission notice appear in supporting documentation.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
18 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
20 * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
21 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
22 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
23 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 *
25 * Except as contained in this notice, the name of a copyright holder
26 * shall not be used in advertising or otherwise to promote the sale, use
27 * or other dealings in this Software without prior written authorization
28 * of the copyright holder.
29 *
30 */
31
32 package org.slf4j.osgi.logservice.impl;
33
34 import org.osgi.framework.Bundle;
35 import org.osgi.framework.ServiceReference;
36 import org.osgi.framework.Version;
37 import org.osgi.service.log.LogService;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42 * <code>LogServiceImpl</code> is a simple OSGi LogService implementation that delegates to a slf4j
43 * Logger.
44 *
45 * @author John Conlon
46 * @author Matt Bishop
47 */
48 public class LogServiceImpl implements LogService {
49
50 private static final String UNKNOWN = "[Unknown]";
51
52 private final Logger delegate;
53
54 /**
55 * Creates a new instance of LogServiceImpl.
56 *
57 * @param bundle The bundle to create a new LogService for.
58 */
59 public LogServiceImpl(Bundle bundle) {
60
61 String name = bundle.getSymbolicName();
62 Version version = bundle.getVersion();
63 if (version == null) {
64 version = Version.emptyVersion;
65 }
66 delegate = LoggerFactory.getLogger(name + '.' + version);
67 }
68
69 /*
70 * (non-Javadoc)
71 *
72 * @see org.osgi.service.log.LogService#log(int, java.lang.String)
73 */
74 public void log(int level, String message) {
75
76 switch (level) {
77 case LOG_DEBUG:
78 delegate.debug(message);
79 break;
80 case LOG_ERROR:
81 delegate.error(message);
82 break;
83 case LOG_INFO:
84 delegate.info(message);
85 break;
86 case LOG_WARNING:
87 delegate.warn(message);
88 break;
89 default:
90 break;
91 }
92 }
93
94 /*
95 * (non-Javadoc)
96 *
97 * @see org.osgi.service.log.LogService#log(int, java.lang.String, java.lang.Throwable)
98 */
99 public void log(int level, String message, Throwable exception) {
100
101 switch (level) {
102 case LOG_DEBUG:
103 delegate.debug(message, exception);
104 break;
105 case LOG_ERROR:
106 delegate.error(message, exception);
107 break;
108 case LOG_INFO:
109 delegate.info(message, exception);
110 break;
111 case LOG_WARNING:
112 delegate.warn(message, exception);
113 break;
114 default:
115 break;
116 }
117 }
118
119 /*
120 * (non-Javadoc)
121 *
122 * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String)
123 */
124 public void log(ServiceReference sr, int level, String message) {
125
126 switch (level) {
127 case LOG_DEBUG:
128 if (delegate.isDebugEnabled()) {
129 delegate.debug(createMessage(sr, message));
130 }
131 break;
132 case LOG_ERROR:
133 if (delegate.isErrorEnabled()) {
134 delegate.error(createMessage(sr, message));
135 }
136 break;
137 case LOG_INFO:
138 if (delegate.isInfoEnabled()) {
139 delegate.info(createMessage(sr, message));
140 }
141 break;
142 case LOG_WARNING:
143 if (delegate.isWarnEnabled()) {
144 delegate.warn(createMessage(sr, message));
145 }
146 break;
147 default:
148 break;
149 }
150 }
151
152 /**
153 * Formats the log message to indicate the service sending it, if known.
154 *
155 * @param sr the ServiceReference sending the message.
156 * @param message The message to log.
157 * @return The formatted log message.
158 */
159 private String createMessage(ServiceReference sr, String message) {
160
161 StringBuilder output = new StringBuilder();
162 if (sr != null) {
163 output.append('[').append(sr.toString()).append(']');
164 } else {
165 output.append(UNKNOWN);
166 }
167 output.append(message);
168
169 return output.toString();
170 }
171
172 /*
173 * (non-Javadoc)
174 *
175 * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String,
176 * java.lang.Throwable)
177 */
178 public void log(ServiceReference sr, int level, String message, Throwable exception) {
179
180 switch (level) {
181 case LOG_DEBUG:
182 if (delegate.isDebugEnabled()) {
183 delegate.debug(createMessage(sr, message), exception);
184 }
185 break;
186 case LOG_ERROR:
187 if (delegate.isErrorEnabled()) {
188 delegate.error(createMessage(sr, message), exception);
189 }
190 break;
191 case LOG_INFO:
192 if (delegate.isInfoEnabled()) {
193 delegate.info(createMessage(sr, message), exception);
194 }
195 break;
196 case LOG_WARNING:
197 if (delegate.isWarnEnabled()) {
198 delegate.warn(createMessage(sr, message), exception);
199 }
200 break;
201 default:
202 break;
203 }
204 }
205 }
0 Implementation-Title: osgi-over-slf4j
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: org.slf4j.osgi-over-slf4j
3 Bundle-Name: OSGi LogService implemented over SLF4J
4 Bundle-RequiredExecutionEnvironment: J2SE-1.5
5 Bundle-Activator: org.slf4j.osgi.logservice.impl.Activator
6 Bundle-Category: osgi
7 Import-Package: org.osgi.framework;version="[1.5,2)",org.osgi.service.log;version="[1.3,2)",org.slf4j;version=${parsedVersion.osgiVersion}
0 Implementation-Title: osgi-over-slf4j
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: org.slf4j.osgi-over-slf4j
3 Bundle-Name: OSGi LogService implemented over SLF4J
4 Bundle-RequiredExecutionEnvironment: J2SE-1.5
5 Bundle-Activator: org.slf4j.osgi.logservice.impl.Activator
6 Bundle-Category: osgi
7 Import-Package: org.osgi.framework;version="[1.5,2)",org.osgi.service.log;version="[1.3,2)",org.slf4j;version=${parsedVersion.osgiVersion}
+427
-424
pom.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <groupId>org.slf4j</groupId>
7 <artifactId>slf4j-parent</artifactId>
8 <version>1.7.25</version>
9
10 <packaging>pom</packaging>
11 <name>SLF4J</name>
12 <description>Top SLF4J project pom.xml file</description>
13 <url>http://www.slf4j.org</url>
14
15 <organization>
16 <name>QOS.ch</name>
17 <url>http://www.qos.ch</url>
18 </organization>
19 <inceptionYear>2005</inceptionYear>
20
21 <licenses>
22 <license>
23 <name>MIT License</name>
24 <url>http://www.opensource.org/licenses/mit-license.php</url>
25 <distribution>repo</distribution>
26 </license>
27 </licenses>
28
29 <scm>
30 <url>https://github.com/qos-ch/slf4j</url>
31 <connection>git@github.com:qos-ch/slf4j.git</connection>
32 </scm>
33
34 <properties>
35 <required.jdk.version>1.5</required.jdk.version>
36 <maven.compiler.source>${required.jdk.version}</maven.compiler.source>
37 <maven.compiler.target>${required.jdk.version}</maven.compiler.target>
38 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
39 <project.build.resourceEncoding>UTF-8</project.build.resourceEncoding>
40 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
41 <!-- used in integration testing -->
42 <slf4j.api.minimum.compatible.version>1.6.0</slf4j.api.minimum.compatible.version>
43 <cal10n.version>0.8.1</cal10n.version>
44 <log4j.version>1.2.17</log4j.version>
45 <logback.version>1.0.13</logback.version>
46 <junit.version>4.12</junit.version>
47 <maven-site-plugin.version>3.3</maven-site-plugin.version>
48 <javadoc.plugin.version>2.10.4</javadoc.plugin.version>
49 </properties>
50
51 <developers>
52 <developer>
53 <id>ceki</id>
54 <name>Ceki Gulcu</name>
55 <email>ceki@qos.ch</email>
56 </developer>
57 </developers>
58
59 <modules>
60 <module>slf4j-api</module>
61 <module>slf4j-simple</module>
62 <module>slf4j-nop</module>
63 <module>slf4j-jdk14</module>
64 <module>slf4j-log4j12</module>
65 <module>slf4j-jcl</module>
66 <module>slf4j-android</module>
67 <module>slf4j-ext</module>
68 <module>jcl-over-slf4j</module>
69 <module>log4j-over-slf4j</module>
70 <module>jul-to-slf4j</module>
71 <module>osgi-over-slf4j</module>
72 <module>integration</module>
73 <module>slf4j-site</module>
74 <module>slf4j-migrator</module>
75 </modules>
76
77 <dependencies>
78 <dependency>
79 <groupId>junit</groupId>
80 <artifactId>junit</artifactId>
81 <version>${junit.version}</version>
82 <scope>test</scope>
83 </dependency>
84 </dependencies>
85
86 <dependencyManagement>
87 <dependencies>
88
89 <dependency>
90 <groupId>org.slf4j</groupId>
91 <artifactId>slf4j-api</artifactId>
92 <version>${project.version}</version>
93 </dependency>
94
95 <dependency>
96 <groupId>org.slf4j</groupId>
97 <artifactId>slf4j-jdk14</artifactId>
98 <version>${project.version}</version>
99 </dependency>
100
101 <dependency>
102 <groupId>log4j</groupId>
103 <artifactId>log4j</artifactId>
104 <version>${log4j.version}</version>
105 </dependency>
106
107 <dependency>
108 <groupId>ch.qos.cal10n</groupId>
109 <artifactId>cal10n-api</artifactId>
110 <version>${cal10n.version}</version>
111 </dependency>
112
113 </dependencies>
114 </dependencyManagement>
115
116 <build>
117 <extensions>
118 <extension>
119 <groupId>org.apache.maven.wagon</groupId>
120 <artifactId>wagon-ssh</artifactId>
121 <version>2.0</version>
122 </extension>
123 </extensions>
124
125 <resources>
126 <resource>
127 <directory>${project.basedir}/src/main/resources</directory>
128 <filtering>true</filtering>
129 </resource>
130 </resources>
131
132 <pluginManagement>
133 <plugins>
134 <plugin>
135 <groupId>org.codehaus.mojo</groupId>
136 <artifactId>animal-sniffer-maven-plugin</artifactId>
137 <version>1.14</version>
138 <configuration>
139 <signature>
140 <groupId>org.codehaus.mojo.signature</groupId>
141 <artifactId>java15</artifactId>
142 <version>1.0</version>
143 </signature>
144 </configuration>
145 </plugin>
146 </plugins>
147 </pluginManagement>
148
149 <plugins>
150
151 <plugin>
152 <groupId>org.apache.maven.plugins</groupId>
153 <artifactId>maven-compiler-plugin</artifactId>
154 <version>3.3</version>
155 <configuration>
156 <source>${required.jdk.version}</source>
157 <target>${required.jdk.version}</target>
158 </configuration>
159 </plugin>
160
161 <plugin>
162 <groupId>org.apache.maven.plugins</groupId>
163 <artifactId>maven-jar-plugin</artifactId>
164 <version>2.3.1</version>
165 <configuration>
166 <archive>
167 <manifestEntries>
168 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
169 <Bundle-Description>${project.description}</Bundle-Description>
170 <X-Compile-Source-JDK>${maven.compiler.source}</X-Compile-Source-JDK>
171 <X-Compile-Target-JDK>${maven.compiler.target}</X-Compile-Target-JDK>
172 <Implementation-Version>${project.version}</Implementation-Version>
173 </manifestEntries>
174 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
175 </archive>
176 <skipIfEmpty>true</skipIfEmpty>
177 </configuration>
178 </plugin>
179
180 <plugin>
181 <groupId>org.apache.maven.plugins</groupId>
182 <artifactId>maven-surefire-plugin</artifactId>
183 <version>2.19.1</version>
184 <configuration>
185 <forkCount>2C</forkCount>
186 <reuseForks>true</reuseForks>
187 <reportFormat>plain</reportFormat>
188 <trimStackTrace>false</trimStackTrace>
189 <excludes>
190 <exclude>**/AllTest.java</exclude>
191 <exclude>**/PackageTest.java</exclude>
192 </excludes>
193 </configuration>
194 </plugin>
195
196 <plugin>
197 <groupId>org.apache.maven.plugins</groupId>
198 <artifactId>maven-source-plugin</artifactId>
199 <version>2.1.2</version>
200 <executions>
201 <execution>
202 <phase>package</phase>
203 <goals>
204 <goal>jar</goal>
205 </goals>
206 </execution>
207 </executions>
208 </plugin>
209
210 <plugin>
211 <groupId>org.apache.maven.plugins</groupId>
212 <artifactId>maven-assembly-plugin</artifactId>
213 <version>2.2</version>
214 <configuration>
215 <descriptors>
216 <descriptor>src/main/assembly/source.xml</descriptor>
217 </descriptors>
218 <finalName>slf4j-${project.version}</finalName>
219 <appendAssemblyId>false</appendAssemblyId>
220 <outputDirectory>target/site/dist/</outputDirectory>
221 </configuration>
222 </plugin>
223
224 <!-- as suggested in http://jira.qos.ch/browse/SLF4J-143 -->
225 <plugin>
226 <groupId>org.codehaus.mojo</groupId>
227 <artifactId>build-helper-maven-plugin</artifactId>
228 <version>1.7</version>
229 <executions>
230 <execution>
231 <id>parse-version</id>
232 <goals>
233 <goal>parse-version</goal>
234 </goals>
235 </execution>
236 </executions>
237 </plugin>
238
239 <!-- ====== site plugin ===== -->
240 <plugin>
241 <groupId>org.apache.maven.plugins</groupId>
242 <artifactId>maven-site-plugin</artifactId>
243 <version>${maven-site-plugin.version}</version>
244 <configuration>
245 <reportPlugins>
246
247 <plugin>
248 <groupId>org.apache.maven.plugins</groupId>
249 <artifactId>maven-jxr-plugin</artifactId>
250 <version>2.3</version>
251 <configuration>
252 <aggregate>true</aggregate>
253 <javadocDir>target/site/apidocs/</javadocDir>
254 <linkJavadoc>true</linkJavadoc>
255 </configuration>
256 </plugin>
257
258 <plugin>
259 <groupId>org.apache.maven.plugins</groupId>
260 <artifactId>maven-javadoc-plugin</artifactId>
261 <version>${javadoc.plugin.version}</version>
262 <configuration>
263 <linksource>true</linksource>
264 <!--<aggregate>true</aggregate>-->
265 <excludePackageNames>org.slf4j.migrator:org.slf4j.migrator.*</excludePackageNames>
266 <links>
267 <link>
268 http://java.sun.com/j2se/1.5.0/docs/api
269 </link>
270 </links>
271 <groups>
272 <group>
273 <title>SLF4J packages</title>
274 <packages>org.slf4j:org.slf4j.*</packages>
275 </group>
276
277 <group>
278 <title>SLF4J extensions</title>
279 <packages>
280 org.slf4j.cal10n:org.slf4j.profiler:org.slf4j.ext:org.slf4j.instrumentation:org.slf4j.agent
281 </packages>
282 </group>
283
284 <group>
285 <title>Jakarta Commons Logging packages</title>
286 <packages>org.apache.commons.*</packages>
287 </group>
288
289 <group>
290 <title>java.util.logging (JUL) to SLF4J bridge</title>
291 <packages>org.slf4j.bridge</packages>
292 </group>
293
294 <group>
295 <title>Apache log4j</title>
296 <packages>org.apache.log4j:org.apache.log4j.*</packages>
297 </group>
298 </groups>
299 </configuration>
300 </plugin>
301
302 </reportPlugins>
303 </configuration>
304 </plugin>
305 </plugins>
306
307 </build>
308
309 <profiles>
310 <profile>
311 <id>skipTests</id>
312 <properties>
313 <maven.test.skip>true</maven.test.skip>
314 </properties>
315 </profile>
316
317 <profile>
318 <id>javadocjar</id>
319 <build>
320 <plugins>
321 <plugin>
322 <groupId>org.apache.maven.plugins</groupId>
323 <artifactId>maven-javadoc-plugin</artifactId>
324 <version>${javadoc.plugin.version}</version>
325 <executions>
326 <execution>
327 <id>attach-javadocs</id>
328 <goals>
329 <goal>jar</goal>
330 </goals>
331 </execution>
332 </executions>
333 </plugin>
334 </plugins>
335 </build>
336 </profile>
337
338 <profile>
339 <id>license</id>
340 <build>
341 <plugins>
342 <plugin>
343 <groupId>com.google.code.maven-license-plugin</groupId>
344 <artifactId>maven-license-plugin</artifactId>
345 <configuration>
346 <header>src/main/licenseHeader.txt</header>
347 <quiet>false</quiet>
348 <failIfMissing>true</failIfMissing>
349 <aggregate>true</aggregate>
350 <includes>
351 <include>src/**/*.java</include>
352 </includes>
353 <useDefaultExcludes>true</useDefaultExcludes>
354 <useDefaultMapping>true</useDefaultMapping>
355 <properties>
356 <year>1999</year>
357 </properties>
358 <headerDefinitions>
359 <headerDefinition>src/main/javadocHeaders.xml</headerDefinition>
360 </headerDefinitions>
361 </configuration>
362 </plugin>
363 </plugins>
364 </build>
365
366 <pluginRepositories>
367 <pluginRepository>
368 <id>mc-release</id>
369 <name>Local Maven repository of releases</name>
370 <url>http://mc-repo.googlecode.com/svn/maven2/releases</url>
371 <snapshots>
372 <enabled>false</enabled>
373 </snapshots>
374 <releases>
375 <enabled>true</enabled>
376 </releases>
377 </pluginRepository>
378 </pluginRepositories>
379 </profile>
380
381 <profile>
382 <id>sign-artifacts</id>
383 <build>
384 <plugins>
385 <plugin>
386 <groupId>org.apache.maven.plugins</groupId>
387 <artifactId>maven-gpg-plugin</artifactId>
388 <version>1.1</version>
389 <executions>
390 <execution>
391 <id>sign-artifacts</id>
392 <phase>verify</phase>
393 <goals>
394 <goal>sign</goal>
395 </goals>
396 </execution>
397 </executions>
398 </plugin>
399 </plugins>
400 </build>
401 </profile>
402
403 </profiles>
404
405 <pluginRepositories>
406 </pluginRepositories>
407
408 <distributionManagement>
409 <site>
410 <id>qos_ch</id>
411 <url>scp://te.qos.ch/var/www/www.slf4j.org/htdocs/</url>
412 </site>
413
414 <repository>
415 <!--<id>pixie</id>-->
416 <!--<url>scp://pixie.qos.ch/var/mvnrepo/</url>-->
417 <id>sonatype-nexus-staging</id>
418 <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
419 </repository>
420
421 </distributionManagement>
422
423 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <groupId>org.slf4j</groupId>
7 <artifactId>slf4j-parent</artifactId>
8 <version>1.7.26</version>
9
10 <packaging>pom</packaging>
11 <name>SLF4J</name>
12 <description>Top SLF4J project pom.xml file</description>
13 <url>http://www.slf4j.org</url>
14
15 <organization>
16 <name>QOS.ch</name>
17 <url>http://www.qos.ch</url>
18 </organization>
19 <inceptionYear>2005</inceptionYear>
20
21 <licenses>
22 <license>
23 <name>MIT License</name>
24 <url>http://www.opensource.org/licenses/mit-license.php</url>
25 <distribution>repo</distribution>
26 </license>
27 </licenses>
28
29 <scm>
30 <url>https://github.com/qos-ch/slf4j</url>
31 <connection>git@github.com:qos-ch/slf4j.git</connection>
32 </scm>
33
34 <properties>
35 <required.jdk.version>1.5</required.jdk.version>
36 <maven.compiler.source>${required.jdk.version}</maven.compiler.source>
37 <maven.compiler.target>${required.jdk.version}</maven.compiler.target>
38 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
39 <project.build.resourceEncoding>UTF-8</project.build.resourceEncoding>
40 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
41 <!-- used in integration testing -->
42 <slf4j.api.minimum.compatible.version>1.6.0</slf4j.api.minimum.compatible.version>
43 <cal10n.version>0.8.1</cal10n.version>
44 <log4j.version>1.2.17</log4j.version>
45 <logback.version>1.0.13</logback.version>
46 <junit.version>4.12</junit.version>
47 <maven-site-plugin.version>3.3</maven-site-plugin.version>
48 <maven-source-plugin.version>3.0.1</maven-source-plugin.version>
49 <javadoc.plugin.version>2.10.4</javadoc.plugin.version>
50 </properties>
51
52 <developers>
53 <developer>
54 <id>ceki</id>
55 <name>Ceki Gulcu</name>
56 <email>ceki@qos.ch</email>
57 </developer>
58 </developers>
59
60 <modules>
61 <module>slf4j-api</module>
62 <module>slf4j-simple</module>
63 <module>slf4j-nop</module>
64 <module>slf4j-jdk14</module>
65 <module>slf4j-log4j12</module>
66 <module>slf4j-jcl</module>
67 <module>slf4j-android</module>
68 <module>slf4j-ext</module>
69 <module>jcl-over-slf4j</module>
70 <module>log4j-over-slf4j</module>
71 <module>jul-to-slf4j</module>
72 <module>osgi-over-slf4j</module>
73 <module>integration</module>
74 <module>slf4j-site</module>
75 <module>slf4j-migrator</module>
76 </modules>
77
78 <dependencies>
79 <dependency>
80 <groupId>junit</groupId>
81 <artifactId>junit</artifactId>
82 <version>${junit.version}</version>
83 <scope>test</scope>
84 </dependency>
85 </dependencies>
86
87 <dependencyManagement>
88 <dependencies>
89
90 <dependency>
91 <groupId>org.slf4j</groupId>
92 <artifactId>slf4j-api</artifactId>
93 <version>${project.version}</version>
94 </dependency>
95
96 <dependency>
97 <groupId>org.slf4j</groupId>
98 <artifactId>slf4j-jdk14</artifactId>
99 <version>${project.version}</version>
100 </dependency>
101
102 <dependency>
103 <groupId>log4j</groupId>
104 <artifactId>log4j</artifactId>
105 <version>${log4j.version}</version>
106 </dependency>
107
108 <dependency>
109 <groupId>ch.qos.cal10n</groupId>
110 <artifactId>cal10n-api</artifactId>
111 <version>${cal10n.version}</version>
112 </dependency>
113
114 </dependencies>
115 </dependencyManagement>
116
117 <build>
118 <extensions>
119 <extension>
120 <groupId>org.apache.maven.wagon</groupId>
121 <artifactId>wagon-ssh</artifactId>
122 <version>2.0</version>
123 </extension>
124 </extensions>
125
126 <resources>
127 <resource>
128 <directory>${project.basedir}/src/main/resources</directory>
129 <filtering>true</filtering>
130 </resource>
131 </resources>
132
133 <pluginManagement>
134 <plugins>
135 <plugin>
136 <groupId>org.codehaus.mojo</groupId>
137 <artifactId>animal-sniffer-maven-plugin</artifactId>
138 <version>1.14</version>
139 <configuration>
140 <signature>
141 <groupId>org.codehaus.mojo.signature</groupId>
142 <artifactId>java15</artifactId>
143 <version>1.0</version>
144 </signature>
145 </configuration>
146 </plugin>
147 </plugins>
148 </pluginManagement>
149
150 <plugins>
151
152 <plugin>
153 <groupId>org.apache.maven.plugins</groupId>
154 <artifactId>maven-compiler-plugin</artifactId>
155 <version>3.3</version>
156 <configuration>
157 <source>${required.jdk.version}</source>
158 <target>${required.jdk.version}</target>
159 </configuration>
160 </plugin>
161
162 <plugin>
163 <groupId>org.apache.maven.plugins</groupId>
164 <artifactId>maven-jar-plugin</artifactId>
165 <version>2.3.1</version>
166 <configuration>
167 <archive>
168 <manifestEntries>
169 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
170 <Bundle-Description>${project.description}</Bundle-Description>
171 <X-Compile-Source-JDK>${maven.compiler.source}</X-Compile-Source-JDK>
172 <X-Compile-Target-JDK>${maven.compiler.target}</X-Compile-Target-JDK>
173 <Implementation-Version>${project.version}</Implementation-Version>
174 </manifestEntries>
175 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
176 </archive>
177 <skipIfEmpty>true</skipIfEmpty>
178 </configuration>
179 </plugin>
180
181 <plugin>
182 <groupId>org.apache.maven.plugins</groupId>
183 <artifactId>maven-source-plugin</artifactId>
184 <version>${maven-source-plugin.version}</version>
185 <executions>
186 <execution>
187 <phase>package</phase>
188 <goals>
189 <goal>jar</goal>
190 </goals>
191 </execution>
192 </executions>
193 </plugin>
194
195 <plugin>
196 <groupId>org.apache.maven.plugins</groupId>
197 <artifactId>maven-surefire-plugin</artifactId>
198 <version>2.19.1</version>
199 <configuration>
200 <forkCount>2C</forkCount>
201 <reuseForks>true</reuseForks>
202 <reportFormat>plain</reportFormat>
203 <trimStackTrace>false</trimStackTrace>
204 <excludes>
205 <exclude>**/AllTest.java</exclude>
206 <exclude>**/PackageTest.java</exclude>
207 </excludes>
208 </configuration>
209 </plugin>
210
211 <plugin>
212 <groupId>org.apache.maven.plugins</groupId>
213 <artifactId>maven-assembly-plugin</artifactId>
214 <version>2.2</version>
215 <configuration>
216 <descriptors>
217 <descriptor>src/main/assembly/source.xml</descriptor>
218 </descriptors>
219 <finalName>slf4j-${project.version}</finalName>
220 <appendAssemblyId>false</appendAssemblyId>
221 <outputDirectory>target/site/dist/</outputDirectory>
222 </configuration>
223 </plugin>
224
225 <!-- as suggested in http://jira.qos.ch/browse/SLF4J-143 -->
226 <plugin>
227 <groupId>org.codehaus.mojo</groupId>
228 <artifactId>build-helper-maven-plugin</artifactId>
229 <version>1.7</version>
230 <executions>
231 <execution>
232 <id>parse-version</id>
233 <goals>
234 <goal>parse-version</goal>
235 </goals>
236 </execution>
237 </executions>
238 </plugin>
239
240 <!-- ====== site plugin ===== -->
241 <plugin>
242 <groupId>org.apache.maven.plugins</groupId>
243 <artifactId>maven-site-plugin</artifactId>
244 <version>${maven-site-plugin.version}</version>
245 <configuration>
246 <reportPlugins>
247
248 <plugin>
249 <groupId>org.apache.maven.plugins</groupId>
250 <artifactId>maven-jxr-plugin</artifactId>
251 <version>2.3</version>
252 <configuration>
253 <aggregate>true</aggregate>
254 <javadocDir>target/site/apidocs/</javadocDir>
255 <linkJavadoc>true</linkJavadoc>
256 </configuration>
257 </plugin>
258
259 <plugin>
260 <groupId>org.apache.maven.plugins</groupId>
261 <artifactId>maven-javadoc-plugin</artifactId>
262 <version>${javadoc.plugin.version}</version>
263 <configuration>
264 <linksource>true</linksource>
265 <doclint>none</doclint>
266
267 <!--<aggregate>true</aggregate>-->
268 <excludePackageNames>org.slf4j.migrator:org.slf4j.migrator.*</excludePackageNames>
269 <links>
270 <link>
271 http://java.sun.com/j2se/1.5.0/docs/api
272 </link>
273 </links>
274 <groups>
275 <group>
276 <title>SLF4J packages</title>
277 <packages>org.slf4j:org.slf4j.*</packages>
278 </group>
279
280 <group>
281 <title>SLF4J extensions</title>
282 <packages>
283 org.slf4j.cal10n:org.slf4j.profiler:org.slf4j.ext:org.slf4j.instrumentation:org.slf4j.agent
284 </packages>
285 </group>
286
287 <group>
288 <title>Jakarta Commons Logging packages</title>
289 <packages>org.apache.commons.*</packages>
290 </group>
291
292 <group>
293 <title>java.util.logging (JUL) to SLF4J bridge</title>
294 <packages>org.slf4j.bridge</packages>
295 </group>
296
297 <group>
298 <title>Apache log4j</title>
299 <packages>org.apache.log4j:org.apache.log4j.*</packages>
300 </group>
301 </groups>
302 </configuration>
303 </plugin>
304
305 </reportPlugins>
306 </configuration>
307 </plugin>
308 </plugins>
309
310 </build>
311
312 <profiles>
313 <profile>
314 <id>skipTests</id>
315 <properties>
316 <maven.test.skip>true</maven.test.skip>
317 </properties>
318 </profile>
319
320 <profile>
321 <id>javadocjar</id>
322 <build>
323 <plugins>
324 <plugin>
325 <groupId>org.apache.maven.plugins</groupId>
326 <artifactId>maven-javadoc-plugin</artifactId>
327 <version>${javadoc.plugin.version}</version>
328 <executions>
329 <execution>
330 <id>attach-javadocs</id>
331 <goals>
332 <goal>jar</goal>
333 </goals>
334 </execution>
335 </executions>
336 </plugin>
337 </plugins>
338 </build>
339 </profile>
340
341 <profile>
342 <id>license</id>
343 <build>
344 <plugins>
345 <plugin>
346 <groupId>com.google.code.maven-license-plugin</groupId>
347 <artifactId>maven-license-plugin</artifactId>
348 <configuration>
349 <header>src/main/licenseHeader.txt</header>
350 <quiet>false</quiet>
351 <failIfMissing>true</failIfMissing>
352 <aggregate>true</aggregate>
353 <includes>
354 <include>src/**/*.java</include>
355 </includes>
356 <useDefaultExcludes>true</useDefaultExcludes>
357 <useDefaultMapping>true</useDefaultMapping>
358 <properties>
359 <year>1999</year>
360 </properties>
361 <headerDefinitions>
362 <headerDefinition>src/main/javadocHeaders.xml</headerDefinition>
363 </headerDefinitions>
364 </configuration>
365 </plugin>
366 </plugins>
367 </build>
368
369 <pluginRepositories>
370 <pluginRepository>
371 <id>mc-release</id>
372 <name>Local Maven repository of releases</name>
373 <url>http://mc-repo.googlecode.com/svn/maven2/releases</url>
374 <snapshots>
375 <enabled>false</enabled>
376 </snapshots>
377 <releases>
378 <enabled>true</enabled>
379 </releases>
380 </pluginRepository>
381 </pluginRepositories>
382 </profile>
383
384 <profile>
385 <id>sign-artifacts</id>
386 <build>
387 <plugins>
388 <plugin>
389 <groupId>org.apache.maven.plugins</groupId>
390 <artifactId>maven-gpg-plugin</artifactId>
391 <version>1.1</version>
392 <executions>
393 <execution>
394 <id>sign-artifacts</id>
395 <phase>verify</phase>
396 <goals>
397 <goal>sign</goal>
398 </goals>
399 </execution>
400 </executions>
401 </plugin>
402 </plugins>
403 </build>
404 </profile>
405
406 </profiles>
407
408 <pluginRepositories>
409 </pluginRepositories>
410
411 <distributionManagement>
412 <site>
413 <id>qos_ch</id>
414 <url>scp://te.qos.ch/var/www/www.slf4j.org/htdocs/</url>
415 </site>
416
417 <repository>
418 <!--<id>pixie</id>-->
419 <!--<url>scp://pixie.qos.ch/var/mvnrepo/</url>-->
420 <id>sonatype-nexus-staging</id>
421 <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
422 </repository>
423
424 </distributionManagement>
425
426 </project>
0 #mvn versions:set -DgenerateBackupPoms=false -DnewVersion=${VERSION_NUMBER}
1
2 MVN='/java/maven-3.5.2//bin/mvn'
3
4 PASS=$1
5 echo $PASS
6
7 function checkExit(){
8 if test "$?" != "0"; then
9 echo Command $1 exited with abnormal status
10 exit 1;
11 else echo $?
12 fi
13 }
14
15 function echoThenRun () { # echo and then run the command
16 echo $1
17 $1
18 ret=$?
19 echo $ret
20 return $ret
21 }
22
23 $MVN clean
24 checkExit "mvn clean"
25
26
27 $MVN install
28 checkExit "mvn install"
29
30
31 $MVN site:site
32 checkExit "mvn site:ste"
33
34
35 $MVN assembly:single
36 checkExit "mvn assembly:single"
37
38
39 $MVN deploy -P javadocjar,sign-artifacts -Dgpg.passphrase=$PASS
40 checkExit "mvn deploy -P javadocjar,sign-artifacts -Dgpg.passphrase=xxx"
41
42 #$MVN site:deploy -N # with Java 8!!!
43 #checkExit "mvn site:deploy -N"
44
45 #git tag -m "tagging" -a v_${VERSION_NUMBER}
46 #git push --tags
47
48 #release version and add next version on jira
0 <?xml version="1.0" encoding="utf-8"?>
1 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2 package="org.slf4j"
3 android:versionCode="176"
4 android:versionName="1.7.6">
5 <uses-sdk android:minSdkVersion="3" />
6 </manifest>
0 Copyright (c) 2004-2013 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>slf4j-android</artifactId>
13 <packaging>jar</packaging>
14 <name>SLF4J Android Binding</name>
15 <description>SLF4J Android Binding</description>
16 <url>http://www.slf4j.org</url>
17
18 <dependencies>
19 <dependency>
20 <groupId>org.slf4j</groupId>
21 <artifactId>slf4j-api</artifactId>
22 <version>${project.version}</version>
23 </dependency>
24
25 <dependency>
26 <groupId>com.google.android</groupId>
27 <artifactId>android</artifactId>
28 <version>1.5_r4</version>
29 <scope>provided</scope>
30 </dependency>
31 </dependencies>
32
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>slf4j-android</artifactId>
13 <packaging>jar</packaging>
14 <name>SLF4J Android Binding</name>
15 <description>SLF4J Android Binding</description>
16 <url>http://www.slf4j.org</url>
17
18 <dependencies>
19 <dependency>
20 <groupId>org.slf4j</groupId>
21 <artifactId>slf4j-api</artifactId>
22 <version>${project.version}</version>
23 </dependency>
24
25 <dependency>
26 <groupId>com.google.android</groupId>
27 <artifactId>android</artifactId>
28 <version>1.5_r4</version>
29 <scope>provided</scope>
30 </dependency>
31 </dependencies>
32
3333 </project>
0 # This file is automatically generated by Android Tools.
1 # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
2 #
3 # This file must be checked in Version Control Systems.
4 #
5 # To customize properties used by the Ant build system use,
6 # "ant.properties", and override values to adapt the script to your
7 # project structure.
8
9 android.library=true
10 # Indicates whether an apk should be generated for each density.
11 split.density=false
12 # Project target.
13 target=android-3
0 /*
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import android.util.Log;
27 import org.slf4j.helpers.FormattingTuple;
28 import org.slf4j.helpers.MarkerIgnoringBase;
29 import org.slf4j.helpers.MessageFormatter;
30
31 /**
32 * <p>A simple implementation that delegates all log requests to the Google Android
33 * logging facilities. Note that this logger does not support {@link org.slf4j.Marker}.
34 * Methods taking marker data as parameter simply invoke the eponymous method
35 * without the Marker argument, discarding any marker data in the process.</p>
36 *
37 * <p>The logging levels specified for SLF4J can be almost directly mapped to
38 * the levels that exist in the Google Android platform. The following table
39 * shows the mapping implemented by this logger.</p>
40 *
41 * <table border="1">
42 * <tr><th><b>SLF4J<b></th><th><b>Android</b></th></tr>
43 * <tr><td>TRACE</td><td>{@link android.util.Log#VERBOSE}</td></tr>
44 * <tr><td>DEBUG</td><td>{@link android.util.Log#DEBUG}</td></tr>
45 * <tr><td>INFO</td><td>{@link android.util.Log#INFO}</td></tr>
46 * <tr><td>WARN</td><td>{@link android.util.Log#WARN}</td></tr>
47 * <tr><td>ERROR</td><td>{@link android.util.Log#ERROR}</td></tr>
48 * </table>
49 *
50 * <p>Use loggers as usual:
51 * <ul>
52 * <li>
53 * Declare a logger<br/>
54 * <code>private static final Logger logger = LoggerFactory.getLogger(MyClass.class);</code>
55 * </li>
56 * <li>
57 * Invoke logging methods, e.g.,<br/>
58 * <code>logger.debug("Some log message. Details: {}", someObject);</code><br/>
59 * <code>logger.debug("Some log message with varargs. Details: {}, {}, {}", someObject1, someObject2, someObject3);</code>
60 * </li>
61 * </ul>
62 * </p>
63 *
64 * <p>Logger instances created using the LoggerFactory are named either according to the name
65 * or the fully qualified class name of the class given as a parameter.
66 * Each logger name will be used as the log message tag on the Android platform.
67 * However, tag names cannot be longer than 23 characters so if logger name exceeds this limit then
68 * it will be truncated by the LoggerFactory. The following examples illustrate this.
69 * <table border="1">
70 * <tr><th><b>Original Name<b></th><th><b>Truncated Name</b></th></tr>
71 * <tr><td>org.example.myproject.mypackage.MyClass</td><td>o*.e*.m*.m*.MyClass</td></tr>
72 * <tr><td>o.e.myproject.mypackage.MyClass</td><td>o.e.m*.m*.MyClass</td></tr>
73 * <tr><td>org.example.ThisNameIsWayTooLongAndWillBeTruncated</td><td>*LongAndWillBeTruncated</td></tr>
74 * <tr><td>ThisNameIsWayTooLongAndWillBeTruncated</td><td>*LongAndWillBeTruncated</td></tr>
75 * </table>
76 * </p>
77 *
78 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
79 */
80 class AndroidLoggerAdapter extends MarkerIgnoringBase {
81 private static final long serialVersionUID = -1227274521521287937L;
82
83 /**
84 * Package access allows only {@link AndroidLoggerFactory} to instantiate
85 * SimpleLogger instances.
86 */
87 AndroidLoggerAdapter(String tag) {
88 this.name = tag;
89 }
90
91 /**
92 * Is this logger instance enabled for the VERBOSE level?
93 *
94 * @return True if this Logger is enabled for level VERBOSE, false otherwise.
95 */
96 public boolean isTraceEnabled() {
97 return isLoggable(Log.VERBOSE);
98 }
99
100 /**
101 * Log a message object at level VERBOSE.
102 *
103 * @param msg
104 * - the message object to be logged
105 */
106 public void trace(String msg) {
107 log(Log.VERBOSE, msg, null);
108 }
109
110 /**
111 * Log a message at level VERBOSE according to the specified format and
112 * argument.
113 *
114 * <p>
115 * This form avoids superfluous object creation when the logger is disabled
116 * for level VERBOSE.
117 * </p>
118 *
119 * @param format
120 * the format string
121 * @param arg
122 * the argument
123 */
124 public void trace(String format, Object arg) {
125 formatAndLog(Log.VERBOSE, format, arg);
126 }
127
128 /**
129 * Log a message at level VERBOSE according to the specified format and
130 * arguments.
131 *
132 * <p>
133 * This form avoids superfluous object creation when the logger is disabled
134 * for the VERBOSE level.
135 * </p>
136 *
137 * @param format
138 * the format string
139 * @param arg1
140 * the first argument
141 * @param arg2
142 * the second argument
143 */
144 public void trace(String format, Object arg1, Object arg2) {
145 formatAndLog(Log.VERBOSE, format, arg1, arg2);
146 }
147
148 /**
149 * Log a message at level VERBOSE according to the specified format and
150 * arguments.
151 *
152 * <p>
153 * This form avoids superfluous object creation when the logger is disabled
154 * for the VERBOSE level.
155 * </p>
156 *
157 * @param format
158 * the format string
159 * @param argArray
160 * an array of arguments
161 */
162 public void trace(String format, Object... argArray) {
163 formatAndLog(Log.VERBOSE, format, argArray);
164 }
165
166 /**
167 * Log an exception (throwable) at level VERBOSE with an accompanying message.
168 *
169 * @param msg
170 * the message accompanying the exception
171 * @param t
172 * the exception (throwable) to log
173 */
174 public void trace(String msg, Throwable t) {
175 log(Log.VERBOSE, msg, t);
176 }
177
178 /**
179 * Is this logger instance enabled for the DEBUG level?
180 *
181 * @return True if this Logger is enabled for level DEBUG, false otherwise.
182 */
183 public boolean isDebugEnabled() {
184 return isLoggable(Log.DEBUG);
185 }
186
187 /**
188 * Log a message object at level DEBUG.
189 *
190 * @param msg
191 * - the message object to be logged
192 */
193 public void debug(String msg) {
194 log(Log.DEBUG, msg, null);
195 }
196
197 /**
198 * Log a message at level DEBUG according to the specified format and argument.
199 *
200 * <p>
201 * This form avoids superfluous object creation when the logger is disabled
202 * for level DEBUG.
203 * </p>
204 *
205 * @param format
206 * the format string
207 * @param arg
208 * the argument
209 */
210 public void debug(String format, Object arg) {
211 formatAndLog(Log.DEBUG, format, arg);
212 }
213
214 /**
215 * Log a message at level DEBUG according to the specified format and
216 * arguments.
217 *
218 * <p>
219 * This form avoids superfluous object creation when the logger is disabled
220 * for the DEBUG level.
221 * </p>
222 *
223 * @param format
224 * the format string
225 * @param arg1
226 * the first argument
227 * @param arg2
228 * the second argument
229 */
230 public void debug(String format, Object arg1, Object arg2) {
231 formatAndLog(Log.DEBUG, format, arg1, arg2);
232 }
233
234 /**
235 * Log a message at level DEBUG according to the specified format and
236 * arguments.
237 *
238 * <p>
239 * This form avoids superfluous object creation when the logger is disabled
240 * for the DEBUG level.
241 * </p>
242 *
243 * @param format
244 * the format string
245 * @param argArray
246 * an array of arguments
247 */
248 public void debug(String format, Object... argArray) {
249 formatAndLog(Log.DEBUG, format, argArray);
250 }
251
252 /**
253 * Log an exception (throwable) at level DEBUG with an accompanying message.
254 *
255 * @param msg
256 * the message accompanying the exception
257 * @param t
258 * the exception (throwable) to log
259 */
260 public void debug(String msg, Throwable t) {
261 log(Log.VERBOSE, msg, t);
262 }
263
264 /**
265 * Is this logger instance enabled for the INFO level?
266 *
267 * @return True if this Logger is enabled for the INFO level, false otherwise.
268 */
269 public boolean isInfoEnabled() {
270 return isLoggable(Log.INFO);
271 }
272
273 /**
274 * Log a message object at the INFO level.
275 *
276 * @param msg
277 * - the message object to be logged
278 */
279 public void info(String msg) {
280 log(Log.INFO, msg, null);
281 }
282
283 /**
284 * Log a message at level INFO according to the specified format and argument.
285 *
286 * <p>
287 * This form avoids superfluous object creation when the logger is disabled
288 * for the INFO level.
289 * </p>
290 *
291 * @param format
292 * the format string
293 * @param arg
294 * the argument
295 */
296 public void info(String format, Object arg) {
297 formatAndLog(Log.INFO, format, arg);
298 }
299
300 /**
301 * Log a message at the INFO level according to the specified format and
302 * arguments.
303 *
304 * <p>
305 * This form avoids superfluous object creation when the logger is disabled
306 * for the INFO level.
307 * </p>
308 *
309 * @param format
310 * the format string
311 * @param arg1
312 * the first argument
313 * @param arg2
314 * the second argument
315 */
316 public void info(String format, Object arg1, Object arg2) {
317 formatAndLog(Log.INFO, format, arg1, arg2);
318 }
319
320 /**
321 * Log a message at level INFO according to the specified format and
322 * arguments.
323 *
324 * <p>
325 * This form avoids superfluous object creation when the logger is disabled
326 * for the INFO level.
327 * </p>
328 *
329 * @param format
330 * the format string
331 * @param argArray
332 * an array of arguments
333 */
334 public void info(String format, Object... argArray) {
335 formatAndLog(Log.INFO, format, argArray);
336 }
337
338 /**
339 * Log an exception (throwable) at the INFO level with an accompanying
340 * message.
341 *
342 * @param msg
343 * the message accompanying the exception
344 * @param t
345 * the exception (throwable) to log
346 */
347 public void info(String msg, Throwable t) {
348 log(Log.INFO, msg, t);
349 }
350
351 /**
352 * Is this logger instance enabled for the WARN level?
353 *
354 * @return True if this Logger is enabled for the WARN level, false
355 * otherwise.
356 */
357 public boolean isWarnEnabled() {
358 return isLoggable(Log.WARN);
359 }
360
361 /**
362 * Log a message object at the WARN level.
363 *
364 * @param msg
365 * - the message object to be logged
366 */
367 public void warn(String msg) {
368 log(Log.WARN, msg, null);
369 }
370
371 /**
372 * Log a message at the WARN level according to the specified format and
373 * argument.
374 *
375 * <p>
376 * This form avoids superfluous object creation when the logger is disabled
377 * for the WARN level.
378 * </p>
379 *
380 * @param format
381 * the format string
382 * @param arg
383 * the argument
384 */
385 public void warn(String format, Object arg) {
386 formatAndLog(Log.WARN, format, arg);
387 }
388
389 /**
390 * Log a message at the WARN level according to the specified format and
391 * arguments.
392 *
393 * <p>
394 * This form avoids superfluous object creation when the logger is disabled
395 * for the WARN level.
396 * </p>
397 *
398 * @param format
399 * the format string
400 * @param arg1
401 * the first argument
402 * @param arg2
403 * the second argument
404 */
405 public void warn(String format, Object arg1, Object arg2) {
406 formatAndLog(Log.WARN, format, arg1, arg2);
407 }
408
409 /**
410 * Log a message at level WARN according to the specified format and
411 * arguments.
412 *
413 * <p>
414 * This form avoids superfluous object creation when the logger is disabled
415 * for the WARN level.
416 * </p>
417 *
418 * @param format
419 * the format string
420 * @param argArray
421 * an array of arguments
422 */
423 public void warn(String format, Object... argArray) {
424 formatAndLog(Log.WARN, format, argArray);
425 }
426
427 /**
428 * Log an exception (throwable) at the WARN level with an accompanying
429 * message.
430 *
431 * @param msg
432 * the message accompanying the exception
433 * @param t
434 * the exception (throwable) to log
435 */
436 public void warn(String msg, Throwable t) {
437 log(Log.WARN, msg, t);
438 }
439
440 /**
441 * Is this logger instance enabled for level ERROR?
442 *
443 * @return True if this Logger is enabled for level ERROR, false otherwise.
444 */
445 public boolean isErrorEnabled() {
446 return isLoggable(Log.ERROR);
447 }
448
449 /**
450 * Log a message object at the ERROR level.
451 *
452 * @param msg
453 * - the message object to be logged
454 */
455 public void error(String msg) {
456 log(Log.ERROR, msg, null);
457 }
458
459 /**
460 * Log a message at the ERROR level according to the specified format and
461 * argument.
462 *
463 * <p>
464 * This form avoids superfluous object creation when the logger is disabled
465 * for the ERROR level.
466 * </p>
467 *
468 * @param format
469 * the format string
470 * @param arg
471 * the argument
472 */
473 public void error(String format, Object arg) {
474 formatAndLog(Log.ERROR, format, arg);
475 }
476
477 /**
478 * Log a message at the ERROR level according to the specified format and
479 * arguments.
480 *
481 * <p>
482 * This form avoids superfluous object creation when the logger is disabled
483 * for the ERROR level.
484 * </p>
485 *
486 * @param format
487 * the format string
488 * @param arg1
489 * the first argument
490 * @param arg2
491 * the second argument
492 */
493 public void error(String format, Object arg1, Object arg2) {
494 formatAndLog(Log.ERROR, format, arg1, arg2);
495 }
496
497 /**
498 * Log a message at level ERROR according to the specified format and
499 * arguments.
500 *
501 * <p>
502 * This form avoids superfluous object creation when the logger is disabled
503 * for the ERROR level.
504 * </p>
505 *
506 * @param format
507 * the format string
508 * @param argArray
509 * an array of arguments
510 */
511 public void error(String format, Object... argArray) {
512 formatAndLog(Log.ERROR, format, argArray);
513 }
514
515 /**
516 * Log an exception (throwable) at the ERROR level with an accompanying
517 * message.
518 *
519 * @param msg
520 * the message accompanying the exception
521 * @param t
522 * the exception (throwable) to log
523 */
524 public void error(String msg, Throwable t) {
525 log(Log.ERROR, msg, t);
526 }
527
528 private void formatAndLog(int priority, String format, Object... argArray) {
529 if (isLoggable(priority)) {
530 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
531 logInternal(priority, ft.getMessage(), ft.getThrowable());
532 }
533 }
534
535 private void log(int priority, String message, Throwable throwable) {
536 if (isLoggable(priority)) {
537 logInternal(priority, message, throwable);
538 }
539 }
540
541 private boolean isLoggable(int priority) {
542 return Log.isLoggable(name, priority);
543 }
544
545 private void logInternal(int priority, String message, Throwable throwable) {
546 if (throwable != null) {
547 message += '\n' + Log.getStackTraceString(throwable);
548 }
549 Log.println(priority, name, message);
550 }
0 /*
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import android.util.Log;
27 import org.slf4j.helpers.FormattingTuple;
28 import org.slf4j.helpers.MarkerIgnoringBase;
29 import org.slf4j.helpers.MessageFormatter;
30
31 /**
32 * <p>A simple implementation that delegates all log requests to the Google Android
33 * logging facilities. Note that this logger does not support {@link org.slf4j.Marker}.
34 * Methods taking marker data as parameter simply invoke the eponymous method
35 * without the Marker argument, discarding any marker data in the process.</p>
36 *
37 * <p>The logging levels specified for SLF4J can be almost directly mapped to
38 * the levels that exist in the Google Android platform. The following table
39 * shows the mapping implemented by this logger.</p>
40 *
41 * <table border="1">
42 * <tr><th><b>SLF4J<b></th><th><b>Android</b></th></tr>
43 * <tr><td>TRACE</td><td>{@link android.util.Log#VERBOSE}</td></tr>
44 * <tr><td>DEBUG</td><td>{@link android.util.Log#DEBUG}</td></tr>
45 * <tr><td>INFO</td><td>{@link android.util.Log#INFO}</td></tr>
46 * <tr><td>WARN</td><td>{@link android.util.Log#WARN}</td></tr>
47 * <tr><td>ERROR</td><td>{@link android.util.Log#ERROR}</td></tr>
48 * </table>
49 *
50 * <p>Use loggers as usual:
51 * <ul>
52 * <li>
53 * Declare a logger<br/>
54 * <code>private static final Logger logger = LoggerFactory.getLogger(MyClass.class);</code>
55 * </li>
56 * <li>
57 * Invoke logging methods, e.g.,<br/>
58 * <code>logger.debug("Some log message. Details: {}", someObject);</code><br/>
59 * <code>logger.debug("Some log message with varargs. Details: {}, {}, {}", someObject1, someObject2, someObject3);</code>
60 * </li>
61 * </ul>
62 * </p>
63 *
64 * <p>Logger instances created using the LoggerFactory are named either according to the name
65 * or the fully qualified class name of the class given as a parameter.
66 * Each logger name will be used as the log message tag on the Android platform.
67 * However, tag names cannot be longer than 23 characters so if logger name exceeds this limit then
68 * it will be truncated by the LoggerFactory. The following examples illustrate this.
69 * <table border="1">
70 * <tr><th><b>Original Name<b></th><th><b>Truncated Name</b></th></tr>
71 * <tr><td>org.example.myproject.mypackage.MyClass</td><td>o*.e*.m*.m*.MyClass</td></tr>
72 * <tr><td>o.e.myproject.mypackage.MyClass</td><td>o.e.m*.m*.MyClass</td></tr>
73 * <tr><td>org.example.ThisNameIsWayTooLongAndWillBeTruncated</td><td>*LongAndWillBeTruncated</td></tr>
74 * <tr><td>ThisNameIsWayTooLongAndWillBeTruncated</td><td>*LongAndWillBeTruncated</td></tr>
75 * </table>
76 * </p>
77 *
78 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
79 */
80 class AndroidLoggerAdapter extends MarkerIgnoringBase {
81 private static final long serialVersionUID = -1227274521521287937L;
82
83 /**
84 * Package access allows only {@link AndroidLoggerFactory} to instantiate
85 * SimpleLogger instances.
86 */
87 AndroidLoggerAdapter(String tag) {
88 this.name = tag;
89 }
90
91 /**
92 * Is this logger instance enabled for the VERBOSE level?
93 *
94 * @return True if this Logger is enabled for level VERBOSE, false otherwise.
95 */
96 public boolean isTraceEnabled() {
97 return isLoggable(Log.VERBOSE);
98 }
99
100 /**
101 * Log a message object at level VERBOSE.
102 *
103 * @param msg
104 * - the message object to be logged
105 */
106 public void trace(String msg) {
107 log(Log.VERBOSE, msg, null);
108 }
109
110 /**
111 * Log a message at level VERBOSE according to the specified format and
112 * argument.
113 *
114 * <p>
115 * This form avoids superfluous object creation when the logger is disabled
116 * for level VERBOSE.
117 * </p>
118 *
119 * @param format
120 * the format string
121 * @param arg
122 * the argument
123 */
124 public void trace(String format, Object arg) {
125 formatAndLog(Log.VERBOSE, format, arg);
126 }
127
128 /**
129 * Log a message at level VERBOSE according to the specified format and
130 * arguments.
131 *
132 * <p>
133 * This form avoids superfluous object creation when the logger is disabled
134 * for the VERBOSE level.
135 * </p>
136 *
137 * @param format
138 * the format string
139 * @param arg1
140 * the first argument
141 * @param arg2
142 * the second argument
143 */
144 public void trace(String format, Object arg1, Object arg2) {
145 formatAndLog(Log.VERBOSE, format, arg1, arg2);
146 }
147
148 /**
149 * Log a message at level VERBOSE according to the specified format and
150 * arguments.
151 *
152 * <p>
153 * This form avoids superfluous object creation when the logger is disabled
154 * for the VERBOSE level.
155 * </p>
156 *
157 * @param format
158 * the format string
159 * @param argArray
160 * an array of arguments
161 */
162 public void trace(String format, Object... argArray) {
163 formatAndLog(Log.VERBOSE, format, argArray);
164 }
165
166 /**
167 * Log an exception (throwable) at level VERBOSE with an accompanying message.
168 *
169 * @param msg
170 * the message accompanying the exception
171 * @param t
172 * the exception (throwable) to log
173 */
174 public void trace(String msg, Throwable t) {
175 log(Log.VERBOSE, msg, t);
176 }
177
178 /**
179 * Is this logger instance enabled for the DEBUG level?
180 *
181 * @return True if this Logger is enabled for level DEBUG, false otherwise.
182 */
183 public boolean isDebugEnabled() {
184 return isLoggable(Log.DEBUG);
185 }
186
187 /**
188 * Log a message object at level DEBUG.
189 *
190 * @param msg
191 * - the message object to be logged
192 */
193 public void debug(String msg) {
194 log(Log.DEBUG, msg, null);
195 }
196
197 /**
198 * Log a message at level DEBUG according to the specified format and argument.
199 *
200 * <p>
201 * This form avoids superfluous object creation when the logger is disabled
202 * for level DEBUG.
203 * </p>
204 *
205 * @param format
206 * the format string
207 * @param arg
208 * the argument
209 */
210 public void debug(String format, Object arg) {
211 formatAndLog(Log.DEBUG, format, arg);
212 }
213
214 /**
215 * Log a message at level DEBUG according to the specified format and
216 * arguments.
217 *
218 * <p>
219 * This form avoids superfluous object creation when the logger is disabled
220 * for the DEBUG level.
221 * </p>
222 *
223 * @param format
224 * the format string
225 * @param arg1
226 * the first argument
227 * @param arg2
228 * the second argument
229 */
230 public void debug(String format, Object arg1, Object arg2) {
231 formatAndLog(Log.DEBUG, format, arg1, arg2);
232 }
233
234 /**
235 * Log a message at level DEBUG according to the specified format and
236 * arguments.
237 *
238 * <p>
239 * This form avoids superfluous object creation when the logger is disabled
240 * for the DEBUG level.
241 * </p>
242 *
243 * @param format
244 * the format string
245 * @param argArray
246 * an array of arguments
247 */
248 public void debug(String format, Object... argArray) {
249 formatAndLog(Log.DEBUG, format, argArray);
250 }
251
252 /**
253 * Log an exception (throwable) at level DEBUG with an accompanying message.
254 *
255 * @param msg
256 * the message accompanying the exception
257 * @param t
258 * the exception (throwable) to log
259 */
260 public void debug(String msg, Throwable t) {
261 log(Log.VERBOSE, msg, t);
262 }
263
264 /**
265 * Is this logger instance enabled for the INFO level?
266 *
267 * @return True if this Logger is enabled for the INFO level, false otherwise.
268 */
269 public boolean isInfoEnabled() {
270 return isLoggable(Log.INFO);
271 }
272
273 /**
274 * Log a message object at the INFO level.
275 *
276 * @param msg
277 * - the message object to be logged
278 */
279 public void info(String msg) {
280 log(Log.INFO, msg, null);
281 }
282
283 /**
284 * Log a message at level INFO according to the specified format and argument.
285 *
286 * <p>
287 * This form avoids superfluous object creation when the logger is disabled
288 * for the INFO level.
289 * </p>
290 *
291 * @param format
292 * the format string
293 * @param arg
294 * the argument
295 */
296 public void info(String format, Object arg) {
297 formatAndLog(Log.INFO, format, arg);
298 }
299
300 /**
301 * Log a message at the INFO level according to the specified format and
302 * arguments.
303 *
304 * <p>
305 * This form avoids superfluous object creation when the logger is disabled
306 * for the INFO level.
307 * </p>
308 *
309 * @param format
310 * the format string
311 * @param arg1
312 * the first argument
313 * @param arg2
314 * the second argument
315 */
316 public void info(String format, Object arg1, Object arg2) {
317 formatAndLog(Log.INFO, format, arg1, arg2);
318 }
319
320 /**
321 * Log a message at level INFO according to the specified format and
322 * arguments.
323 *
324 * <p>
325 * This form avoids superfluous object creation when the logger is disabled
326 * for the INFO level.
327 * </p>
328 *
329 * @param format
330 * the format string
331 * @param argArray
332 * an array of arguments
333 */
334 public void info(String format, Object... argArray) {
335 formatAndLog(Log.INFO, format, argArray);
336 }
337
338 /**
339 * Log an exception (throwable) at the INFO level with an accompanying
340 * message.
341 *
342 * @param msg
343 * the message accompanying the exception
344 * @param t
345 * the exception (throwable) to log
346 */
347 public void info(String msg, Throwable t) {
348 log(Log.INFO, msg, t);
349 }
350
351 /**
352 * Is this logger instance enabled for the WARN level?
353 *
354 * @return True if this Logger is enabled for the WARN level, false
355 * otherwise.
356 */
357 public boolean isWarnEnabled() {
358 return isLoggable(Log.WARN);
359 }
360
361 /**
362 * Log a message object at the WARN level.
363 *
364 * @param msg
365 * - the message object to be logged
366 */
367 public void warn(String msg) {
368 log(Log.WARN, msg, null);
369 }
370
371 /**
372 * Log a message at the WARN level according to the specified format and
373 * argument.
374 *
375 * <p>
376 * This form avoids superfluous object creation when the logger is disabled
377 * for the WARN level.
378 * </p>
379 *
380 * @param format
381 * the format string
382 * @param arg
383 * the argument
384 */
385 public void warn(String format, Object arg) {
386 formatAndLog(Log.WARN, format, arg);
387 }
388
389 /**
390 * Log a message at the WARN level according to the specified format and
391 * arguments.
392 *
393 * <p>
394 * This form avoids superfluous object creation when the logger is disabled
395 * for the WARN level.
396 * </p>
397 *
398 * @param format
399 * the format string
400 * @param arg1
401 * the first argument
402 * @param arg2
403 * the second argument
404 */
405 public void warn(String format, Object arg1, Object arg2) {
406 formatAndLog(Log.WARN, format, arg1, arg2);
407 }
408
409 /**
410 * Log a message at level WARN according to the specified format and
411 * arguments.
412 *
413 * <p>
414 * This form avoids superfluous object creation when the logger is disabled
415 * for the WARN level.
416 * </p>
417 *
418 * @param format
419 * the format string
420 * @param argArray
421 * an array of arguments
422 */
423 public void warn(String format, Object... argArray) {
424 formatAndLog(Log.WARN, format, argArray);
425 }
426
427 /**
428 * Log an exception (throwable) at the WARN level with an accompanying
429 * message.
430 *
431 * @param msg
432 * the message accompanying the exception
433 * @param t
434 * the exception (throwable) to log
435 */
436 public void warn(String msg, Throwable t) {
437 log(Log.WARN, msg, t);
438 }
439
440 /**
441 * Is this logger instance enabled for level ERROR?
442 *
443 * @return True if this Logger is enabled for level ERROR, false otherwise.
444 */
445 public boolean isErrorEnabled() {
446 return isLoggable(Log.ERROR);
447 }
448
449 /**
450 * Log a message object at the ERROR level.
451 *
452 * @param msg
453 * - the message object to be logged
454 */
455 public void error(String msg) {
456 log(Log.ERROR, msg, null);
457 }
458
459 /**
460 * Log a message at the ERROR level according to the specified format and
461 * argument.
462 *
463 * <p>
464 * This form avoids superfluous object creation when the logger is disabled
465 * for the ERROR level.
466 * </p>
467 *
468 * @param format
469 * the format string
470 * @param arg
471 * the argument
472 */
473 public void error(String format, Object arg) {
474 formatAndLog(Log.ERROR, format, arg);
475 }
476
477 /**
478 * Log a message at the ERROR level according to the specified format and
479 * arguments.
480 *
481 * <p>
482 * This form avoids superfluous object creation when the logger is disabled
483 * for the ERROR level.
484 * </p>
485 *
486 * @param format
487 * the format string
488 * @param arg1
489 * the first argument
490 * @param arg2
491 * the second argument
492 */
493 public void error(String format, Object arg1, Object arg2) {
494 formatAndLog(Log.ERROR, format, arg1, arg2);
495 }
496
497 /**
498 * Log a message at level ERROR according to the specified format and
499 * arguments.
500 *
501 * <p>
502 * This form avoids superfluous object creation when the logger is disabled
503 * for the ERROR level.
504 * </p>
505 *
506 * @param format
507 * the format string
508 * @param argArray
509 * an array of arguments
510 */
511 public void error(String format, Object... argArray) {
512 formatAndLog(Log.ERROR, format, argArray);
513 }
514
515 /**
516 * Log an exception (throwable) at the ERROR level with an accompanying
517 * message.
518 *
519 * @param msg
520 * the message accompanying the exception
521 * @param t
522 * the exception (throwable) to log
523 */
524 public void error(String msg, Throwable t) {
525 log(Log.ERROR, msg, t);
526 }
527
528 private void formatAndLog(int priority, String format, Object... argArray) {
529 if (isLoggable(priority)) {
530 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
531 logInternal(priority, ft.getMessage(), ft.getThrowable());
532 }
533 }
534
535 private void log(int priority, String message, Throwable throwable) {
536 if (isLoggable(priority)) {
537 logInternal(priority, message, throwable);
538 }
539 }
540
541 private boolean isLoggable(int priority) {
542 return Log.isLoggable(name, priority);
543 }
544
545 private void logInternal(int priority, String message, Throwable throwable) {
546 if (throwable != null) {
547 message += '\n' + Log.getStackTraceString(throwable);
548 }
549 Log.println(priority, name, message);
550 }
551551 }
0 /*
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.Logger;
28
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31
32 /**
33 * AndroidLoggerFactory is an implementation of {@link ILoggerFactory} returning
34 * the appropriately named {@link AndroidLoggerFactory} instance.
35 *
36 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
37 */
38 class AndroidLoggerFactory implements ILoggerFactory {
39 static final String ANONYMOUS_TAG = "null";
40 static final int TAG_MAX_LENGTH = 23;
41
42 private final ConcurrentMap<String, Logger> loggerMap = new ConcurrentHashMap<String, Logger>();
43
44 /**
45 * Return an appropriate {@link AndroidLoggerAdapter} instance by name.
46 */
47 public Logger getLogger(String name) {
48 String tag = loggerNameToTag(name);
49 Logger logger = loggerMap.get(tag);
50 if (logger == null) {
51 Logger newInstance = new AndroidLoggerAdapter(tag);
52 Logger oldInstance = loggerMap.putIfAbsent(tag, newInstance);
53 logger = oldInstance == null ? newInstance : oldInstance;
54 }
55 return logger;
56 }
57
58 /**
59 * Tag names cannot be longer than {@value #TAG_MAX_LENGTH} characters on Android platform.
60 *
61 * Returns the short logger tag (up to {@value #TAG_MAX_LENGTH} characters) for the given logger name.
62 * Traditionally loggers are named by fully-qualified Java classes; this
63 * method attempts to return a concise identifying part of such names.
64 *
65 * See also:
66 * android/system/core/include/cutils/property.h
67 * android/frameworks/base/core/jni/android_util_Log.cpp
68 * dalvik.system.DalvikLogging
69 *
70 */
71 static String loggerNameToTag(String loggerName) {
72 // Anonymous logger
73 if (loggerName == null) {
74 return ANONYMOUS_TAG;
75 }
76
77 int length = loggerName.length();
78 if (length <= TAG_MAX_LENGTH) {
79 return loggerName;
80 }
81
82 int tagLength = 0;
83 int lastTokenIndex = 0;
84 int lastPeriodIndex;
85 StringBuilder tagName = new StringBuilder(TAG_MAX_LENGTH + 3);
86 while ((lastPeriodIndex = loggerName.indexOf('.', lastTokenIndex)) != -1) {
87 tagName.append(loggerName.charAt(lastTokenIndex));
88 // token of one character appended as is otherwise truncate it to one character
89 int tokenLength = lastPeriodIndex - lastTokenIndex;
90 if (tokenLength > 1) {
91 tagName.append('*');
92 }
93 tagName.append('.');
94 lastTokenIndex = lastPeriodIndex + 1;
95
96 // check if name is already too long
97 tagLength = tagName.length();
98 if (tagLength > TAG_MAX_LENGTH) {
99 return getSimpleName(loggerName);
100 }
101 }
102
103 // Either we had no useful dot location at all
104 // or last token would exceed TAG_MAX_LENGTH
105 int tokenLength = length - lastTokenIndex;
106 if (tagLength == 0 || (tagLength + tokenLength) > TAG_MAX_LENGTH) {
107 return getSimpleName(loggerName);
108 }
109
110 // last token (usually class name) appended as is
111 tagName.append(loggerName, lastTokenIndex, length);
112 return tagName.toString();
113 }
114
115 private static String getSimpleName(String loggerName) {
116 // Take leading part and append '*' to indicate that it was truncated
117 int length = loggerName.length();
118 int lastPeriodIndex = loggerName.lastIndexOf('.');
119 return lastPeriodIndex != -1 && length - (lastPeriodIndex + 1) <= TAG_MAX_LENGTH ? loggerName.substring(lastPeriodIndex + 1) : '*' + loggerName
120 .substring(length - TAG_MAX_LENGTH + 1);
121 }
0 /*
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.Logger;
28
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31
32 /**
33 * AndroidLoggerFactory is an implementation of {@link ILoggerFactory} returning
34 * the appropriately named {@link AndroidLoggerFactory} instance.
35 *
36 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
37 */
38 class AndroidLoggerFactory implements ILoggerFactory {
39 static final String ANONYMOUS_TAG = "null";
40 static final int TAG_MAX_LENGTH = 23;
41
42 private final ConcurrentMap<String, Logger> loggerMap = new ConcurrentHashMap<String, Logger>();
43
44 /**
45 * Return an appropriate {@link AndroidLoggerAdapter} instance by name.
46 */
47 public Logger getLogger(String name) {
48 String tag = loggerNameToTag(name);
49 Logger logger = loggerMap.get(tag);
50 if (logger == null) {
51 Logger newInstance = new AndroidLoggerAdapter(tag);
52 Logger oldInstance = loggerMap.putIfAbsent(tag, newInstance);
53 logger = oldInstance == null ? newInstance : oldInstance;
54 }
55 return logger;
56 }
57
58 /**
59 * Tag names cannot be longer than {@value #TAG_MAX_LENGTH} characters on Android platform.
60 *
61 * Returns the short logger tag (up to {@value #TAG_MAX_LENGTH} characters) for the given logger name.
62 * Traditionally loggers are named by fully-qualified Java classes; this
63 * method attempts to return a concise identifying part of such names.
64 *
65 * See also:
66 * android/system/core/include/cutils/property.h
67 * android/frameworks/base/core/jni/android_util_Log.cpp
68 * dalvik.system.DalvikLogging
69 *
70 */
71 static String loggerNameToTag(String loggerName) {
72 // Anonymous logger
73 if (loggerName == null) {
74 return ANONYMOUS_TAG;
75 }
76
77 int length = loggerName.length();
78 if (length <= TAG_MAX_LENGTH) {
79 return loggerName;
80 }
81
82 int tagLength = 0;
83 int lastTokenIndex = 0;
84 int lastPeriodIndex;
85 StringBuilder tagName = new StringBuilder(TAG_MAX_LENGTH + 3);
86 while ((lastPeriodIndex = loggerName.indexOf('.', lastTokenIndex)) != -1) {
87 tagName.append(loggerName.charAt(lastTokenIndex));
88 // token of one character appended as is otherwise truncate it to one character
89 int tokenLength = lastPeriodIndex - lastTokenIndex;
90 if (tokenLength > 1) {
91 tagName.append('*');
92 }
93 tagName.append('.');
94 lastTokenIndex = lastPeriodIndex + 1;
95
96 // check if name is already too long
97 tagLength = tagName.length();
98 if (tagLength > TAG_MAX_LENGTH) {
99 return getSimpleName(loggerName);
100 }
101 }
102
103 // Either we had no useful dot location at all
104 // or last token would exceed TAG_MAX_LENGTH
105 int tokenLength = length - lastTokenIndex;
106 if (tagLength == 0 || (tagLength + tokenLength) > TAG_MAX_LENGTH) {
107 return getSimpleName(loggerName);
108 }
109
110 // last token (usually class name) appended as is
111 tagName.append(loggerName, lastTokenIndex, length);
112 return tagName.toString();
113 }
114
115 private static String getSimpleName(String loggerName) {
116 // Take leading part and append '*' to indicate that it was truncated
117 int length = loggerName.length();
118 int lastPeriodIndex = loggerName.lastIndexOf('.');
119 return lastPeriodIndex != -1 && length - (lastPeriodIndex + 1) <= TAG_MAX_LENGTH ? loggerName.substring(lastPeriodIndex + 1) : '*' + loggerName
120 .substring(length - TAG_MAX_LENGTH + 1);
121 }
122122 }
0 /**
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
36 */
37 public class StaticLoggerBinder implements LoggerFactoryBinder {
38
39 /**
40 * The unique instance of this class.
41 */
42 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticLoggerBinder singleton
48 */
49 public static StaticLoggerBinder getSingleton() {
50 return SINGLETON;
51 }
52
53 /**
54 * Declare the version of the SLF4J API this implementation is compiled against.
55 * The value of this field is modified with each major release.
56 */
57 // to avoid constant folding by the compiler, this field must *not* be final
58 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
59
60 private static final String loggerFactoryClassStr = AndroidLoggerFactory.class.getName();
61
62 /**
63 * The ILoggerFactory instance returned by the {@link #getLoggerFactory} method
64 * should always be the same object
65 */
66 private final ILoggerFactory loggerFactory;
67
68 private StaticLoggerBinder() {
69 loggerFactory = new AndroidLoggerFactory();
70 }
71
72 public ILoggerFactory getLoggerFactory() {
73 return loggerFactory;
74 }
75
76 public String getLoggerFactoryClassStr() {
77 return loggerFactoryClassStr;
78 }
79 }
0 /**
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
36 */
37 public class StaticLoggerBinder implements LoggerFactoryBinder {
38
39 /**
40 * The unique instance of this class.
41 */
42 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticLoggerBinder singleton
48 */
49 public static StaticLoggerBinder getSingleton() {
50 return SINGLETON;
51 }
52
53 /**
54 * Declare the version of the SLF4J API this implementation is compiled against.
55 * The value of this field is modified with each major release.
56 */
57 // to avoid constant folding by the compiler, this field must *not* be final
58 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
59
60 private static final String loggerFactoryClassStr = AndroidLoggerFactory.class.getName();
61
62 /**
63 * The ILoggerFactory instance returned by the {@link #getLoggerFactory} method
64 * should always be the same object
65 */
66 private final ILoggerFactory loggerFactory;
67
68 private StaticLoggerBinder() {
69 loggerFactory = new AndroidLoggerFactory();
70 }
71
72 public ILoggerFactory getLoggerFactory() {
73 return loggerFactory;
74 }
75
76 public String getLoggerFactoryClassStr() {
77 return loggerFactoryClassStr;
78 }
79 }
0 /**
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link NOPMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
34 */
35 public class StaticMDCBinder {
36
37 /**
38 * The unique instance of this class.
39 */
40 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
41
42 private StaticMDCBinder() {
43 }
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticMDCBinder singleton
49 * @since 1.7.14
50 */
51 public static final StaticMDCBinder getSingleton() {
52 return SINGLETON;
53 }
54
55 /**
56 * Currently this method always returns an instance of
57 * {@link NOPMDCAdapter}.
58 */
59 public MDCAdapter getMDCA() {
60 return new NOPMDCAdapter();
61 }
62
63 public String getMDCAdapterClassStr() {
64 return NOPMDCAdapter.class.getName();
65 }
66 }
0 /**
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link NOPMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
34 */
35 public class StaticMDCBinder {
36
37 /**
38 * The unique instance of this class.
39 */
40 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
41
42 private StaticMDCBinder() {
43 }
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticMDCBinder singleton
49 * @since 1.7.14
50 */
51 public static final StaticMDCBinder getSingleton() {
52 return SINGLETON;
53 }
54
55 /**
56 * Currently this method always returns an instance of
57 * {@link NOPMDCAdapter}.
58 */
59 public MDCAdapter getMDCA() {
60 return new NOPMDCAdapter();
61 }
62
63 public String getMDCAdapterClassStr() {
64 return NOPMDCAdapter.class.getName();
65 }
66 }
0 /**
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
38 */
39 public class StaticMarkerBinder implements MarkerFactoryBinder {
40
41 /**
42 * The unique instance of this class.
43 */
44 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
45
46 final IMarkerFactory markerFactory = new BasicMarkerFactory();
47
48 private StaticMarkerBinder() {
49 }
50
51 /**
52 * Return the singleton of this class.
53 *
54 * @return the StaticMarkerBinder singleton
55 * @since 1.7.14
56 */
57 public static StaticMarkerBinder getSingleton() {
58 return SINGLETON;
59 }
60
61 /**
62 * Currently this method always returns an instance of
63 * {@link BasicMarkerFactory}.
64 */
65 public IMarkerFactory getMarkerFactory() {
66 return markerFactory;
67 }
68
69 /**
70 * Currently, this method returns the class name of
71 * {@link BasicMarkerFactory}.
72 */
73 public String getMarkerFactoryClassStr() {
74 return BasicMarkerFactory.class.getName();
75 }
76 }
0 /**
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
38 */
39 public class StaticMarkerBinder implements MarkerFactoryBinder {
40
41 /**
42 * The unique instance of this class.
43 */
44 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
45
46 final IMarkerFactory markerFactory = new BasicMarkerFactory();
47
48 private StaticMarkerBinder() {
49 }
50
51 /**
52 * Return the singleton of this class.
53 *
54 * @return the StaticMarkerBinder singleton
55 * @since 1.7.14
56 */
57 public static StaticMarkerBinder getSingleton() {
58 return SINGLETON;
59 }
60
61 /**
62 * Currently this method always returns an instance of
63 * {@link BasicMarkerFactory}.
64 */
65 public IMarkerFactory getMarkerFactory() {
66 return markerFactory;
67 }
68
69 /**
70 * Currently, this method returns the class name of
71 * {@link BasicMarkerFactory}.
72 */
73 public String getMarkerFactoryClassStr() {
74 return BasicMarkerFactory.class.getName();
75 }
76 }
0 Implementation-Title: slf4j-android
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.android
3 Bundle-Name: slf4j-android
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}
0 Implementation-Title: slf4j-android
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.android
3 Bundle-Name: slf4j-android
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}
88 Fragment-Host: slf4j.api
0 /*
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.junit.Test;
27
28 import static org.junit.Assert.assertEquals;
29
30 public class AndroidLoggerFactoryTest {
31 @Test
32 public void shortLoggerNames() {
33 assertEquals("o.test.p.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.p.TestClass"));
34 assertEquals("ex.test.TestClass", AndroidLoggerFactory.loggerNameToTag("ex.test.TestClass"));
35 assertEquals("MyClass", AndroidLoggerFactory.loggerNameToTag("MyClass"));
36 }
37
38 @Test
39 public void emptyLoggerNames() {
40 assertEquals(AndroidLoggerFactory.ANONYMOUS_TAG, AndroidLoggerFactory.loggerNameToTag(null));
41 assertEquals("", AndroidLoggerFactory.loggerNameToTag(""));
42 }
43
44 @Test
45 public void simpleLoggerName() {
46 assertEquals("o*.t*.p*.TestClass", AndroidLoggerFactory.loggerNameToTag("org.test.package.TestClass"));
47 }
48
49 @Test
50 public void loggerNameWithOneCharPackage() {
51 assertEquals("o.t*.p*.p*.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.project.package.TestClass"));
52 assertEquals("o.t*.p*.p.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.project.p.TestClass"));
53 }
54
55 @Test
56 public void longLoggerName() {
57 assertEquals("AndroidLoggerFactory", AndroidLoggerFactory.loggerNameToTag("org.slf4j.impl.AndroidLoggerFactory"));
58 }
59
60 @Test
61 public void veryLongLoggerName() {
62 assertEquals("*meAndShouldBeTruncated", AndroidLoggerFactory.loggerNameToTag("IAmAVeryLongLoggerNameAndShouldBeTruncated"));
63 }
64
65 @Test
66 public void oneWordLoggerName() {
67 assertEquals("TestClass", AndroidLoggerFactory.loggerNameToTag("TestClass"));
68 }
69
70 @Test
71 public void weirdLoggerNames() {
72 assertEquals("WeirdLoggerName.", AndroidLoggerFactory.loggerNameToTag("WeirdLoggerName."));
73 assertEquals(".WeirdLoggerName", AndroidLoggerFactory.loggerNameToTag(".WeirdLoggerName"));
74 assertEquals(".WeirdLoggerName.", AndroidLoggerFactory.loggerNameToTag(".WeirdLoggerName."));
75 assertEquals(".", AndroidLoggerFactory.loggerNameToTag("."));
76 assertEquals("..", AndroidLoggerFactory.loggerNameToTag(".."));
77 }
78 }
0 /*
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.junit.Test;
27
28 import static org.junit.Assert.assertEquals;
29
30 public class AndroidLoggerFactoryTest {
31 @Test
32 public void shortLoggerNames() {
33 assertEquals("o.test.p.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.p.TestClass"));
34 assertEquals("ex.test.TestClass", AndroidLoggerFactory.loggerNameToTag("ex.test.TestClass"));
35 assertEquals("MyClass", AndroidLoggerFactory.loggerNameToTag("MyClass"));
36 }
37
38 @Test
39 public void emptyLoggerNames() {
40 assertEquals(AndroidLoggerFactory.ANONYMOUS_TAG, AndroidLoggerFactory.loggerNameToTag(null));
41 assertEquals("", AndroidLoggerFactory.loggerNameToTag(""));
42 }
43
44 @Test
45 public void simpleLoggerName() {
46 assertEquals("o*.t*.p*.TestClass", AndroidLoggerFactory.loggerNameToTag("org.test.package.TestClass"));
47 }
48
49 @Test
50 public void loggerNameWithOneCharPackage() {
51 assertEquals("o.t*.p*.p*.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.project.package.TestClass"));
52 assertEquals("o.t*.p*.p.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.project.p.TestClass"));
53 }
54
55 @Test
56 public void longLoggerName() {
57 assertEquals("AndroidLoggerFactory", AndroidLoggerFactory.loggerNameToTag("org.slf4j.impl.AndroidLoggerFactory"));
58 }
59
60 @Test
61 public void veryLongLoggerName() {
62 assertEquals("*meAndShouldBeTruncated", AndroidLoggerFactory.loggerNameToTag("IAmAVeryLongLoggerNameAndShouldBeTruncated"));
63 }
64
65 @Test
66 public void oneWordLoggerName() {
67 assertEquals("TestClass", AndroidLoggerFactory.loggerNameToTag("TestClass"));
68 }
69
70 @Test
71 public void weirdLoggerNames() {
72 assertEquals("WeirdLoggerName.", AndroidLoggerFactory.loggerNameToTag("WeirdLoggerName."));
73 assertEquals(".WeirdLoggerName", AndroidLoggerFactory.loggerNameToTag(".WeirdLoggerName"));
74 assertEquals(".WeirdLoggerName.", AndroidLoggerFactory.loggerNameToTag(".WeirdLoggerName."));
75 assertEquals(".", AndroidLoggerFactory.loggerNameToTag("."));
76 assertEquals("..", AndroidLoggerFactory.loggerNameToTag(".."));
77 }
78 }
0 Copyright (c) 2004-2007 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>slf4j-api</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J API Module</name>
16 <description>The slf4j API</description>
17
18 <url>http://www.slf4j.org</url>
19
20 <build>
21 <plugins>
22 <plugin>
23 <groupId>org.codehaus.mojo</groupId>
24 <artifactId>animal-sniffer-maven-plugin</artifactId>
25 <configuration>
26 <!-- Signatures cannot be determined and will error unless excluded. This is isolated to
27 code otherwise already marked for removal in the module artifact. -->
28 <ignores>
29 <ignore>org.slf4j.impl.StaticMDCBinder</ignore>
30 <ignore>org.slf4j.impl.StaticLoggerBinder</ignore>
31 <ignore>org.slf4j.impl.StaticMarkerBinder</ignore>
32 </ignores>
33 </configuration>
34 </plugin>
35 <plugin>
36 <groupId>org.apache.maven.plugins</groupId>
37 <artifactId>maven-surefire-plugin</artifactId>
38 <configuration>
39 <forkMode>once</forkMode>
40 <reportFormat>plain</reportFormat>
41 <trimStackTrace>false</trimStackTrace>
42 <excludes>
43 <exclude>**/AllTest.java</exclude>
44 <exclude>**/PackageTest.java</exclude>
45 </excludes>
46 </configuration>
47 </plugin>
48
49 <plugin>
50 <groupId>org.apache.maven.plugins</groupId>
51 <artifactId>maven-jar-plugin</artifactId>
52 <executions>
53 <execution>
54 <id>bundle-test-jar</id>
55 <phase>package</phase>
56 <goals>
57 <goal>jar</goal>
58 <goal>test-jar</goal>
59 </goals>
60 </execution>
61 </executions>
62 </plugin>
63
64 <plugin>
65 <groupId>org.apache.maven.plugins</groupId>
66 <artifactId>maven-antrun-plugin</artifactId>
67 <executions>
68 <execution>
69 <phase>process-classes</phase>
70 <goals>
71 <goal>run</goal>
72 </goals>
73 </execution>
74 </executions>
75 <configuration>
76 <tasks>
77 <echo>Removing slf4j-api's dummy StaticLoggerBinder and StaticMarkerBinder</echo>
78 <delete dir="target/classes/org/slf4j/impl"/>
79 </tasks>
80 </configuration>
81 </plugin>
82 </plugins>
83
84 <pluginManagement>
85 <plugins>
86 <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
87 <plugin>
88 <groupId>org.eclipse.m2e</groupId>
89 <artifactId>lifecycle-mapping</artifactId>
90 <version>1.0.0</version>
91 <configuration>
92 <lifecycleMappingMetadata>
93 <pluginExecutions>
94 <pluginExecution>
95 <pluginExecutionFilter>
96 <groupId>
97 org.apache.maven.plugins
98 </groupId>
99 <artifactId>
100 maven-antrun-plugin
101 </artifactId>
102 <versionRange>[1.3,)</versionRange>
103 <goals>
104 <goal>run</goal>
105 </goals>
106 </pluginExecutionFilter>
107 <action>
108 <ignore></ignore>
109 </action>
110 </pluginExecution>
111 </pluginExecutions>
112 </lifecycleMappingMetadata>
113 </configuration>
114 </plugin>
115 </plugins>
116 </pluginManagement>
117 </build>
118
119 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>slf4j-api</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J API Module</name>
16 <description>The slf4j API</description>
17
18 <url>http://www.slf4j.org</url>
19
20 <build>
21 <plugins>
22 <plugin>
23 <groupId>org.codehaus.mojo</groupId>
24 <artifactId>animal-sniffer-maven-plugin</artifactId>
25 <configuration>
26 <!-- Signatures cannot be determined and will error unless excluded. This is isolated to
27 code otherwise already marked for removal in the module artifact. -->
28 <ignores>
29 <ignore>org.slf4j.impl.StaticMDCBinder</ignore>
30 <ignore>org.slf4j.impl.StaticLoggerBinder</ignore>
31 <ignore>org.slf4j.impl.StaticMarkerBinder</ignore>
32 </ignores>
33 </configuration>
34 </plugin>
35 <plugin>
36 <groupId>org.apache.maven.plugins</groupId>
37 <artifactId>maven-surefire-plugin</artifactId>
38 <configuration>
39 <forkMode>once</forkMode>
40 <reportFormat>plain</reportFormat>
41 <trimStackTrace>false</trimStackTrace>
42 <excludes>
43 <exclude>**/AllTest.java</exclude>
44 <exclude>**/PackageTest.java</exclude>
45 </excludes>
46 </configuration>
47 </plugin>
48
49 <plugin>
50 <groupId>org.apache.maven.plugins</groupId>
51 <artifactId>maven-jar-plugin</artifactId>
52 <executions>
53 <execution>
54 <id>bundle-test-jar</id>
55 <phase>package</phase>
56 <goals>
57 <goal>jar</goal>
58 <goal>test-jar</goal>
59 </goals>
60 </execution>
61 </executions>
62 </plugin>
63
64 <plugin>
65 <groupId>org.apache.maven.plugins</groupId>
66 <artifactId>maven-antrun-plugin</artifactId>
67 <executions>
68 <execution>
69 <phase>process-classes</phase>
70 <goals>
71 <goal>run</goal>
72 </goals>
73 </execution>
74 </executions>
75 <configuration>
76 <tasks>
77 <echo>Removing slf4j-api's dummy StaticLoggerBinder and StaticMarkerBinder</echo>
78 <delete dir="target/classes/org/slf4j/impl"/>
79 </tasks>
80 </configuration>
81 </plugin>
82 </plugins>
83
84 <pluginManagement>
85 <plugins>
86 <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
87 <plugin>
88 <groupId>org.eclipse.m2e</groupId>
89 <artifactId>lifecycle-mapping</artifactId>
90 <version>1.0.0</version>
91 <configuration>
92 <lifecycleMappingMetadata>
93 <pluginExecutions>
94 <pluginExecution>
95 <pluginExecutionFilter>
96 <groupId>
97 org.apache.maven.plugins
98 </groupId>
99 <artifactId>
100 maven-antrun-plugin
101 </artifactId>
102 <versionRange>[1.3,)</versionRange>
103 <goals>
104 <goal>run</goal>
105 </goals>
106 </pluginExecutionFilter>
107 <action>
108 <ignore></ignore>
109 </action>
110 </pluginExecution>
111 </pluginExecutions>
112 </lifecycleMappingMetadata>
113 </configuration>
114 </plugin>
115 </plugins>
116 </pluginManagement>
117 </build>
118
119 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 /**
27 * <code>ILoggerFactory</code> instances manufacture {@link Logger}
28 * instances by name.
29 *
30 * <p>Most users retrieve {@link Logger} instances through the static
31 * {@link LoggerFactory#getLogger(String)} method. An instance of of this
32 * interface is bound internally with {@link LoggerFactory} class at
33 * compile time.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public interface ILoggerFactory {
38
39 /**
40 * Return an appropriate {@link Logger} instance as specified by the
41 * <code>name</code> parameter.
42 *
43 * <p>If the name parameter is equal to {@link Logger#ROOT_LOGGER_NAME}, that is
44 * the string value "ROOT" (case insensitive), then the root logger of the
45 * underlying logging system is returned.
46 *
47 * <p>Null-valued name arguments are considered invalid.
48 *
49 * <p>Certain extremely simple logging systems, e.g. NOP, may always
50 * return the same logger instance regardless of the requested name.
51 *
52 * @param name the name of the Logger to return
53 * @return a Logger instance
54 */
55 public Logger getLogger(String name);
56 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 /**
27 * <code>ILoggerFactory</code> instances manufacture {@link Logger}
28 * instances by name.
29 *
30 * <p>Most users retrieve {@link Logger} instances through the static
31 * {@link LoggerFactory#getLogger(String)} method. An instance of of this
32 * interface is bound internally with {@link LoggerFactory} class at
33 * compile time.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public interface ILoggerFactory {
38
39 /**
40 * Return an appropriate {@link Logger} instance as specified by the
41 * <code>name</code> parameter.
42 *
43 * <p>If the name parameter is equal to {@link Logger#ROOT_LOGGER_NAME}, that is
44 * the string value "ROOT" (case insensitive), then the root logger of the
45 * underlying logging system is returned.
46 *
47 * <p>Null-valued name arguments are considered invalid.
48 *
49 * <p>Certain extremely simple logging systems, e.g. NOP, may always
50 * return the same logger instance regardless of the requested name.
51 *
52 * @param name the name of the Logger to return
53 * @return a Logger instance
54 */
55 public Logger getLogger(String name);
56 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 /**
27 * Implementations of this interface are used to manufacture {@link Marker}
28 * instances.
29 *
30 * <p>See the section <a href="http://slf4j.org/faq.html#3">Implementing
31 * the SLF4J API</a> in the FAQ for details on how to make your logging
32 * system conform to SLF4J.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public interface IMarkerFactory {
37
38 /**
39 * Manufacture a {@link Marker} instance by name. If the instance has been
40 * created earlier, return the previously created instance.
41 *
42 * <p>Null name values are not allowed.
43 *
44 * @param name the name of the marker to be created, null value is
45 * not allowed.
46 *
47 * @return a Marker instance
48 */
49 Marker getMarker(String name);
50
51 /**
52 * Checks if the marker with the name already exists. If name is null, then false
53 * is returned.
54 *
55 * @param name logger name to check for
56 * @return true id the marker exists, false otherwise.
57 */
58 boolean exists(String name);
59
60 /**
61 * Detach an existing marker.
62 * <p>
63 * Note that after a marker is detached, there might still be "dangling" references
64 * to the detached marker.
65 *
66 *
67 * @param name The name of the marker to detach
68 * @return whether the marker could be detached or not
69 */
70 boolean detachMarker(String name);
71
72 /**
73 * Create a marker which is detached (even at birth) from this IMarkerFactory.
74 *
75 * @param name marker name
76 * @return a dangling marker
77 * @since 1.5.1
78 */
79 Marker getDetachedMarker(String name);
80 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 /**
27 * Implementations of this interface are used to manufacture {@link Marker}
28 * instances.
29 *
30 * <p>See the section <a href="http://slf4j.org/faq.html#3">Implementing
31 * the SLF4J API</a> in the FAQ for details on how to make your logging
32 * system conform to SLF4J.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public interface IMarkerFactory {
37
38 /**
39 * Manufacture a {@link Marker} instance by name. If the instance has been
40 * created earlier, return the previously created instance.
41 *
42 * <p>Null name values are not allowed.
43 *
44 * @param name the name of the marker to be created, null value is
45 * not allowed.
46 *
47 * @return a Marker instance
48 */
49 Marker getMarker(String name);
50
51 /**
52 * Checks if the marker with the name already exists. If name is null, then false
53 * is returned.
54 *
55 * @param name logger name to check for
56 * @return true id the marker exists, false otherwise.
57 */
58 boolean exists(String name);
59
60 /**
61 * Detach an existing marker.
62 * <p>
63 * Note that after a marker is detached, there might still be "dangling" references
64 * to the detached marker.
65 *
66 *
67 * @param name The name of the marker to detach
68 * @return whether the marker could be detached or not
69 */
70 boolean detachMarker(String name);
71
72 /**
73 * Create a marker which is detached (even at birth) from this IMarkerFactory.
74 *
75 * @param name marker name
76 * @return a dangling marker
77 * @since 1.5.1
78 */
79 Marker getDetachedMarker(String name);
80 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j;
26
27 /**
28 * The org.slf4j.Logger interface is the main user entry point of SLF4J API.
29 * It is expected that logging takes place through concrete implementations
30 * of this interface.
31 * <p/>
32 * <h3>Typical usage pattern:</h3>
33 * <pre>
34 * import org.slf4j.Logger;
35 * import org.slf4j.LoggerFactory;
36 *
37 * public class Wombat {
38 *
39 * <span style="color:green">final static Logger logger = LoggerFactory.getLogger(Wombat.class);</span>
40 * Integer t;
41 * Integer oldT;
42 *
43 * public void setTemperature(Integer temperature) {
44 * oldT = t;
45 * t = temperature;
46 * <span style="color:green">logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);</span>
47 * if(temperature.intValue() > 50) {
48 * <span style="color:green">logger.info("Temperature has risen above 50 degrees.");</span>
49 * }
50 * }
51 * }
52 * </pre>
53 *
54 * Be sure to read the FAQ entry relating to <a href="../../../faq.html#logging_performance">parameterized
55 * logging</a>. Note that logging statements can be parameterized in
56 * <a href="../../../faq.html#paramException">presence of an exception/throwable</a>.
57 *
58 * <p>Once you are comfortable using loggers, i.e. instances of this interface, consider using
59 * <a href="MDC.html">MDC</a> as well as <a href="Marker.html">Markers</a>.</p>
60 *
61 * @author Ceki G&uuml;lc&uuml;
62 */
63 public interface Logger {
64
65 /**
66 * Case insensitive String constant used to retrieve the name of the root logger.
67 *
68 * @since 1.3
69 */
70 final public String ROOT_LOGGER_NAME = "ROOT";
71
72 /**
73 * Return the name of this <code>Logger</code> instance.
74 * @return name of this logger instance
75 */
76 public String getName();
77
78 /**
79 * Is the logger instance enabled for the TRACE level?
80 *
81 * @return True if this Logger is enabled for the TRACE level,
82 * false otherwise.
83 * @since 1.4
84 */
85 public boolean isTraceEnabled();
86
87 /**
88 * Log a message at the TRACE level.
89 *
90 * @param msg the message string to be logged
91 * @since 1.4
92 */
93 public void trace(String msg);
94
95 /**
96 * Log a message at the TRACE level according to the specified format
97 * and argument.
98 * <p/>
99 * <p>This form avoids superfluous object creation when the logger
100 * is disabled for the TRACE level. </p>
101 *
102 * @param format the format string
103 * @param arg the argument
104 * @since 1.4
105 */
106 public void trace(String format, Object arg);
107
108 /**
109 * Log a message at the TRACE level according to the specified format
110 * and arguments.
111 * <p/>
112 * <p>This form avoids superfluous object creation when the logger
113 * is disabled for the TRACE level. </p>
114 *
115 * @param format the format string
116 * @param arg1 the first argument
117 * @param arg2 the second argument
118 * @since 1.4
119 */
120 public void trace(String format, Object arg1, Object arg2);
121
122 /**
123 * Log a message at the TRACE level according to the specified format
124 * and arguments.
125 * <p/>
126 * <p>This form avoids superfluous string concatenation when the logger
127 * is disabled for the TRACE level. However, this variant incurs the hidden
128 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
129 * even if this logger is disabled for TRACE. The variants taking {@link #trace(String, Object) one} and
130 * {@link #trace(String, Object, Object) two} arguments exist solely in order to avoid this hidden cost.</p>
131 *
132 * @param format the format string
133 * @param arguments a list of 3 or more arguments
134 * @since 1.4
135 */
136 public void trace(String format, Object... arguments);
137
138 /**
139 * Log an exception (throwable) at the TRACE level with an
140 * accompanying message.
141 *
142 * @param msg the message accompanying the exception
143 * @param t the exception (throwable) to log
144 * @since 1.4
145 */
146 public void trace(String msg, Throwable t);
147
148 /**
149 * Similar to {@link #isTraceEnabled()} method except that the
150 * marker data is also taken into account.
151 *
152 * @param marker The marker data to take into consideration
153 * @return True if this Logger is enabled for the TRACE level,
154 * false otherwise.
155 *
156 * @since 1.4
157 */
158 public boolean isTraceEnabled(Marker marker);
159
160 /**
161 * Log a message with the specific Marker at the TRACE level.
162 *
163 * @param marker the marker data specific to this log statement
164 * @param msg the message string to be logged
165 * @since 1.4
166 */
167 public void trace(Marker marker, String msg);
168
169 /**
170 * This method is similar to {@link #trace(String, Object)} method except that the
171 * marker data is also taken into consideration.
172 *
173 * @param marker the marker data specific to this log statement
174 * @param format the format string
175 * @param arg the argument
176 * @since 1.4
177 */
178 public void trace(Marker marker, String format, Object arg);
179
180 /**
181 * This method is similar to {@link #trace(String, Object, Object)}
182 * method except that the marker data is also taken into
183 * consideration.
184 *
185 * @param marker the marker data specific to this log statement
186 * @param format the format string
187 * @param arg1 the first argument
188 * @param arg2 the second argument
189 * @since 1.4
190 */
191 public void trace(Marker marker, String format, Object arg1, Object arg2);
192
193 /**
194 * This method is similar to {@link #trace(String, Object...)}
195 * method except that the marker data is also taken into
196 * consideration.
197 *
198 * @param marker the marker data specific to this log statement
199 * @param format the format string
200 * @param argArray an array of arguments
201 * @since 1.4
202 */
203 public void trace(Marker marker, String format, Object... argArray);
204
205 /**
206 * This method is similar to {@link #trace(String, Throwable)} method except that the
207 * marker data is also taken into consideration.
208 *
209 * @param marker the marker data specific to this log statement
210 * @param msg the message accompanying the exception
211 * @param t the exception (throwable) to log
212 * @since 1.4
213 */
214 public void trace(Marker marker, String msg, Throwable t);
215
216 /**
217 * Is the logger instance enabled for the DEBUG level?
218 *
219 * @return True if this Logger is enabled for the DEBUG level,
220 * false otherwise.
221 */
222 public boolean isDebugEnabled();
223
224 /**
225 * Log a message at the DEBUG level.
226 *
227 * @param msg the message string to be logged
228 */
229 public void debug(String msg);
230
231 /**
232 * Log a message at the DEBUG level according to the specified format
233 * and argument.
234 * <p/>
235 * <p>This form avoids superfluous object creation when the logger
236 * is disabled for the DEBUG level. </p>
237 *
238 * @param format the format string
239 * @param arg the argument
240 */
241 public void debug(String format, Object arg);
242
243 /**
244 * Log a message at the DEBUG level according to the specified format
245 * and arguments.
246 * <p/>
247 * <p>This form avoids superfluous object creation when the logger
248 * is disabled for the DEBUG level. </p>
249 *
250 * @param format the format string
251 * @param arg1 the first argument
252 * @param arg2 the second argument
253 */
254 public void debug(String format, Object arg1, Object arg2);
255
256 /**
257 * Log a message at the DEBUG level according to the specified format
258 * and arguments.
259 * <p/>
260 * <p>This form avoids superfluous string concatenation when the logger
261 * is disabled for the DEBUG level. However, this variant incurs the hidden
262 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
263 * even if this logger is disabled for DEBUG. The variants taking
264 * {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
265 * arguments exist solely in order to avoid this hidden cost.</p>
266 *
267 * @param format the format string
268 * @param arguments a list of 3 or more arguments
269 */
270 public void debug(String format, Object... arguments);
271
272 /**
273 * Log an exception (throwable) at the DEBUG level with an
274 * accompanying message.
275 *
276 * @param msg the message accompanying the exception
277 * @param t the exception (throwable) to log
278 */
279 public void debug(String msg, Throwable t);
280
281 /**
282 * Similar to {@link #isDebugEnabled()} method except that the
283 * marker data is also taken into account.
284 *
285 * @param marker The marker data to take into consideration
286 * @return True if this Logger is enabled for the DEBUG level,
287 * false otherwise.
288 */
289 public boolean isDebugEnabled(Marker marker);
290
291 /**
292 * Log a message with the specific Marker at the DEBUG level.
293 *
294 * @param marker the marker data specific to this log statement
295 * @param msg the message string to be logged
296 */
297 public void debug(Marker marker, String msg);
298
299 /**
300 * This method is similar to {@link #debug(String, Object)} method except that the
301 * marker data is also taken into consideration.
302 *
303 * @param marker the marker data specific to this log statement
304 * @param format the format string
305 * @param arg the argument
306 */
307 public void debug(Marker marker, String format, Object arg);
308
309 /**
310 * This method is similar to {@link #debug(String, Object, Object)}
311 * method except that the marker data is also taken into
312 * consideration.
313 *
314 * @param marker the marker data specific to this log statement
315 * @param format the format string
316 * @param arg1 the first argument
317 * @param arg2 the second argument
318 */
319 public void debug(Marker marker, String format, Object arg1, Object arg2);
320
321 /**
322 * This method is similar to {@link #debug(String, Object...)}
323 * method except that the marker data is also taken into
324 * consideration.
325 *
326 * @param marker the marker data specific to this log statement
327 * @param format the format string
328 * @param arguments a list of 3 or more arguments
329 */
330 public void debug(Marker marker, String format, Object... arguments);
331
332 /**
333 * This method is similar to {@link #debug(String, Throwable)} method except that the
334 * marker data is also taken into consideration.
335 *
336 * @param marker the marker data specific to this log statement
337 * @param msg the message accompanying the exception
338 * @param t the exception (throwable) to log
339 */
340 public void debug(Marker marker, String msg, Throwable t);
341
342 /**
343 * Is the logger instance enabled for the INFO level?
344 *
345 * @return True if this Logger is enabled for the INFO level,
346 * false otherwise.
347 */
348 public boolean isInfoEnabled();
349
350 /**
351 * Log a message at the INFO level.
352 *
353 * @param msg the message string to be logged
354 */
355 public void info(String msg);
356
357 /**
358 * Log a message at the INFO level according to the specified format
359 * and argument.
360 * <p/>
361 * <p>This form avoids superfluous object creation when the logger
362 * is disabled for the INFO level. </p>
363 *
364 * @param format the format string
365 * @param arg the argument
366 */
367 public void info(String format, Object arg);
368
369 /**
370 * Log a message at the INFO level according to the specified format
371 * and arguments.
372 * <p/>
373 * <p>This form avoids superfluous object creation when the logger
374 * is disabled for the INFO level. </p>
375 *
376 * @param format the format string
377 * @param arg1 the first argument
378 * @param arg2 the second argument
379 */
380 public void info(String format, Object arg1, Object arg2);
381
382 /**
383 * Log a message at the INFO level according to the specified format
384 * and arguments.
385 * <p/>
386 * <p>This form avoids superfluous string concatenation when the logger
387 * is disabled for the INFO level. However, this variant incurs the hidden
388 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
389 * even if this logger is disabled for INFO. The variants taking
390 * {@link #info(String, Object) one} and {@link #info(String, Object, Object) two}
391 * arguments exist solely in order to avoid this hidden cost.</p>
392 *
393 * @param format the format string
394 * @param arguments a list of 3 or more arguments
395 */
396 public void info(String format, Object... arguments);
397
398 /**
399 * Log an exception (throwable) at the INFO level with an
400 * accompanying message.
401 *
402 * @param msg the message accompanying the exception
403 * @param t the exception (throwable) to log
404 */
405 public void info(String msg, Throwable t);
406
407 /**
408 * Similar to {@link #isInfoEnabled()} method except that the marker
409 * data is also taken into consideration.
410 *
411 * @param marker The marker data to take into consideration
412 * @return true if this logger is warn enabled, false otherwise
413 */
414 public boolean isInfoEnabled(Marker marker);
415
416 /**
417 * Log a message with the specific Marker at the INFO level.
418 *
419 * @param marker The marker specific to this log statement
420 * @param msg the message string to be logged
421 */
422 public void info(Marker marker, String msg);
423
424 /**
425 * This method is similar to {@link #info(String, Object)} method except that the
426 * marker data is also taken into consideration.
427 *
428 * @param marker the marker data specific to this log statement
429 * @param format the format string
430 * @param arg the argument
431 */
432 public void info(Marker marker, String format, Object arg);
433
434 /**
435 * This method is similar to {@link #info(String, Object, Object)}
436 * method except that the marker data is also taken into
437 * consideration.
438 *
439 * @param marker the marker data specific to this log statement
440 * @param format the format string
441 * @param arg1 the first argument
442 * @param arg2 the second argument
443 */
444 public void info(Marker marker, String format, Object arg1, Object arg2);
445
446 /**
447 * This method is similar to {@link #info(String, Object...)}
448 * method except that the marker data is also taken into
449 * consideration.
450 *
451 * @param marker the marker data specific to this log statement
452 * @param format the format string
453 * @param arguments a list of 3 or more arguments
454 */
455 public void info(Marker marker, String format, Object... arguments);
456
457 /**
458 * This method is similar to {@link #info(String, Throwable)} method
459 * except that the marker data is also taken into consideration.
460 *
461 * @param marker the marker data for this log statement
462 * @param msg the message accompanying the exception
463 * @param t the exception (throwable) to log
464 */
465 public void info(Marker marker, String msg, Throwable t);
466
467 /**
468 * Is the logger instance enabled for the WARN level?
469 *
470 * @return True if this Logger is enabled for the WARN level,
471 * false otherwise.
472 */
473 public boolean isWarnEnabled();
474
475 /**
476 * Log a message at the WARN level.
477 *
478 * @param msg the message string to be logged
479 */
480 public void warn(String msg);
481
482 /**
483 * Log a message at the WARN level according to the specified format
484 * and argument.
485 * <p/>
486 * <p>This form avoids superfluous object creation when the logger
487 * is disabled for the WARN level. </p>
488 *
489 * @param format the format string
490 * @param arg the argument
491 */
492 public void warn(String format, Object arg);
493
494 /**
495 * Log a message at the WARN level according to the specified format
496 * and arguments.
497 * <p/>
498 * <p>This form avoids superfluous string concatenation when the logger
499 * is disabled for the WARN level. However, this variant incurs the hidden
500 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
501 * even if this logger is disabled for WARN. The variants taking
502 * {@link #warn(String, Object) one} and {@link #warn(String, Object, Object) two}
503 * arguments exist solely in order to avoid this hidden cost.</p>
504 *
505 * @param format the format string
506 * @param arguments a list of 3 or more arguments
507 */
508 public void warn(String format, Object... arguments);
509
510 /**
511 * Log a message at the WARN level according to the specified format
512 * and arguments.
513 * <p/>
514 * <p>This form avoids superfluous object creation when the logger
515 * is disabled for the WARN level. </p>
516 *
517 * @param format the format string
518 * @param arg1 the first argument
519 * @param arg2 the second argument
520 */
521 public void warn(String format, Object arg1, Object arg2);
522
523 /**
524 * Log an exception (throwable) at the WARN level with an
525 * accompanying message.
526 *
527 * @param msg the message accompanying the exception
528 * @param t the exception (throwable) to log
529 */
530 public void warn(String msg, Throwable t);
531
532 /**
533 * Similar to {@link #isWarnEnabled()} method except that the marker
534 * data is also taken into consideration.
535 *
536 * @param marker The marker data to take into consideration
537 * @return True if this Logger is enabled for the WARN level,
538 * false otherwise.
539 */
540 public boolean isWarnEnabled(Marker marker);
541
542 /**
543 * Log a message with the specific Marker at the WARN level.
544 *
545 * @param marker The marker specific to this log statement
546 * @param msg the message string to be logged
547 */
548 public void warn(Marker marker, String msg);
549
550 /**
551 * This method is similar to {@link #warn(String, Object)} method except that the
552 * marker data is also taken into consideration.
553 *
554 * @param marker the marker data specific to this log statement
555 * @param format the format string
556 * @param arg the argument
557 */
558 public void warn(Marker marker, String format, Object arg);
559
560 /**
561 * This method is similar to {@link #warn(String, Object, Object)}
562 * method except that the marker data is also taken into
563 * consideration.
564 *
565 * @param marker the marker data specific to this log statement
566 * @param format the format string
567 * @param arg1 the first argument
568 * @param arg2 the second argument
569 */
570 public void warn(Marker marker, String format, Object arg1, Object arg2);
571
572 /**
573 * This method is similar to {@link #warn(String, Object...)}
574 * method except that the marker data is also taken into
575 * consideration.
576 *
577 * @param marker the marker data specific to this log statement
578 * @param format the format string
579 * @param arguments a list of 3 or more arguments
580 */
581 public void warn(Marker marker, String format, Object... arguments);
582
583 /**
584 * This method is similar to {@link #warn(String, Throwable)} method
585 * except that the marker data is also taken into consideration.
586 *
587 * @param marker the marker data for this log statement
588 * @param msg the message accompanying the exception
589 * @param t the exception (throwable) to log
590 */
591 public void warn(Marker marker, String msg, Throwable t);
592
593 /**
594 * Is the logger instance enabled for the ERROR level?
595 *
596 * @return True if this Logger is enabled for the ERROR level,
597 * false otherwise.
598 */
599 public boolean isErrorEnabled();
600
601 /**
602 * Log a message at the ERROR level.
603 *
604 * @param msg the message string to be logged
605 */
606 public void error(String msg);
607
608 /**
609 * Log a message at the ERROR level according to the specified format
610 * and argument.
611 * <p/>
612 * <p>This form avoids superfluous object creation when the logger
613 * is disabled for the ERROR level. </p>
614 *
615 * @param format the format string
616 * @param arg the argument
617 */
618 public void error(String format, Object arg);
619
620 /**
621 * Log a message at the ERROR level according to the specified format
622 * and arguments.
623 * <p/>
624 * <p>This form avoids superfluous object creation when the logger
625 * is disabled for the ERROR level. </p>
626 *
627 * @param format the format string
628 * @param arg1 the first argument
629 * @param arg2 the second argument
630 */
631 public void error(String format, Object arg1, Object arg2);
632
633 /**
634 * Log a message at the ERROR level according to the specified format
635 * and arguments.
636 * <p/>
637 * <p>This form avoids superfluous string concatenation when the logger
638 * is disabled for the ERROR level. However, this variant incurs the hidden
639 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
640 * even if this logger is disabled for ERROR. The variants taking
641 * {@link #error(String, Object) one} and {@link #error(String, Object, Object) two}
642 * arguments exist solely in order to avoid this hidden cost.</p>
643 *
644 * @param format the format string
645 * @param arguments a list of 3 or more arguments
646 */
647 public void error(String format, Object... arguments);
648
649 /**
650 * Log an exception (throwable) at the ERROR level with an
651 * accompanying message.
652 *
653 * @param msg the message accompanying the exception
654 * @param t the exception (throwable) to log
655 */
656 public void error(String msg, Throwable t);
657
658 /**
659 * Similar to {@link #isErrorEnabled()} method except that the
660 * marker data is also taken into consideration.
661 *
662 * @param marker The marker data to take into consideration
663 * @return True if this Logger is enabled for the ERROR level,
664 * false otherwise.
665 */
666 public boolean isErrorEnabled(Marker marker);
667
668 /**
669 * Log a message with the specific Marker at the ERROR level.
670 *
671 * @param marker The marker specific to this log statement
672 * @param msg the message string to be logged
673 */
674 public void error(Marker marker, String msg);
675
676 /**
677 * This method is similar to {@link #error(String, Object)} method except that the
678 * marker data is also taken into consideration.
679 *
680 * @param marker the marker data specific to this log statement
681 * @param format the format string
682 * @param arg the argument
683 */
684 public void error(Marker marker, String format, Object arg);
685
686 /**
687 * This method is similar to {@link #error(String, Object, Object)}
688 * method except that the marker data is also taken into
689 * consideration.
690 *
691 * @param marker the marker data specific to this log statement
692 * @param format the format string
693 * @param arg1 the first argument
694 * @param arg2 the second argument
695 */
696 public void error(Marker marker, String format, Object arg1, Object arg2);
697
698 /**
699 * This method is similar to {@link #error(String, Object...)}
700 * method except that the marker data is also taken into
701 * consideration.
702 *
703 * @param marker the marker data specific to this log statement
704 * @param format the format string
705 * @param arguments a list of 3 or more arguments
706 */
707 public void error(Marker marker, String format, Object... arguments);
708
709 /**
710 * This method is similar to {@link #error(String, Throwable)}
711 * method except that the marker data is also taken into
712 * consideration.
713 *
714 * @param marker the marker data specific to this log statement
715 * @param msg the message accompanying the exception
716 * @param t the exception (throwable) to log
717 */
718 public void error(Marker marker, String msg, Throwable t);
719
720 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j;
26
27 /**
28 * The org.slf4j.Logger interface is the main user entry point of SLF4J API.
29 * It is expected that logging takes place through concrete implementations
30 * of this interface.
31 * <p/>
32 * <h3>Typical usage pattern:</h3>
33 * <pre>
34 * import org.slf4j.Logger;
35 * import org.slf4j.LoggerFactory;
36 *
37 * public class Wombat {
38 *
39 * <span style="color:green">final static Logger logger = LoggerFactory.getLogger(Wombat.class);</span>
40 * Integer t;
41 * Integer oldT;
42 *
43 * public void setTemperature(Integer temperature) {
44 * oldT = t;
45 * t = temperature;
46 * <span style="color:green">logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);</span>
47 * if(temperature.intValue() > 50) {
48 * <span style="color:green">logger.info("Temperature has risen above 50 degrees.");</span>
49 * }
50 * }
51 * }
52 * </pre>
53 *
54 * Be sure to read the FAQ entry relating to <a href="../../../faq.html#logging_performance">parameterized
55 * logging</a>. Note that logging statements can be parameterized in
56 * <a href="../../../faq.html#paramException">presence of an exception/throwable</a>.
57 *
58 * <p>Once you are comfortable using loggers, i.e. instances of this interface, consider using
59 * <a href="MDC.html">MDC</a> as well as <a href="Marker.html">Markers</a>.</p>
60 *
61 * @author Ceki G&uuml;lc&uuml;
62 */
63 public interface Logger {
64
65 /**
66 * Case insensitive String constant used to retrieve the name of the root logger.
67 *
68 * @since 1.3
69 */
70 final public String ROOT_LOGGER_NAME = "ROOT";
71
72 /**
73 * Return the name of this <code>Logger</code> instance.
74 * @return name of this logger instance
75 */
76 public String getName();
77
78 /**
79 * Is the logger instance enabled for the TRACE level?
80 *
81 * @return True if this Logger is enabled for the TRACE level,
82 * false otherwise.
83 * @since 1.4
84 */
85 public boolean isTraceEnabled();
86
87 /**
88 * Log a message at the TRACE level.
89 *
90 * @param msg the message string to be logged
91 * @since 1.4
92 */
93 public void trace(String msg);
94
95 /**
96 * Log a message at the TRACE level according to the specified format
97 * and argument.
98 * <p/>
99 * <p>This form avoids superfluous object creation when the logger
100 * is disabled for the TRACE level. </p>
101 *
102 * @param format the format string
103 * @param arg the argument
104 * @since 1.4
105 */
106 public void trace(String format, Object arg);
107
108 /**
109 * Log a message at the TRACE level according to the specified format
110 * and arguments.
111 * <p/>
112 * <p>This form avoids superfluous object creation when the logger
113 * is disabled for the TRACE level. </p>
114 *
115 * @param format the format string
116 * @param arg1 the first argument
117 * @param arg2 the second argument
118 * @since 1.4
119 */
120 public void trace(String format, Object arg1, Object arg2);
121
122 /**
123 * Log a message at the TRACE level according to the specified format
124 * and arguments.
125 * <p/>
126 * <p>This form avoids superfluous string concatenation when the logger
127 * is disabled for the TRACE level. However, this variant incurs the hidden
128 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
129 * even if this logger is disabled for TRACE. The variants taking {@link #trace(String, Object) one} and
130 * {@link #trace(String, Object, Object) two} arguments exist solely in order to avoid this hidden cost.</p>
131 *
132 * @param format the format string
133 * @param arguments a list of 3 or more arguments
134 * @since 1.4
135 */
136 public void trace(String format, Object... arguments);
137
138 /**
139 * Log an exception (throwable) at the TRACE level with an
140 * accompanying message.
141 *
142 * @param msg the message accompanying the exception
143 * @param t the exception (throwable) to log
144 * @since 1.4
145 */
146 public void trace(String msg, Throwable t);
147
148 /**
149 * Similar to {@link #isTraceEnabled()} method except that the
150 * marker data is also taken into account.
151 *
152 * @param marker The marker data to take into consideration
153 * @return True if this Logger is enabled for the TRACE level,
154 * false otherwise.
155 *
156 * @since 1.4
157 */
158 public boolean isTraceEnabled(Marker marker);
159
160 /**
161 * Log a message with the specific Marker at the TRACE level.
162 *
163 * @param marker the marker data specific to this log statement
164 * @param msg the message string to be logged
165 * @since 1.4
166 */
167 public void trace(Marker marker, String msg);
168
169 /**
170 * This method is similar to {@link #trace(String, Object)} method except that the
171 * marker data is also taken into consideration.
172 *
173 * @param marker the marker data specific to this log statement
174 * @param format the format string
175 * @param arg the argument
176 * @since 1.4
177 */
178 public void trace(Marker marker, String format, Object arg);
179
180 /**
181 * This method is similar to {@link #trace(String, Object, Object)}
182 * method except that the marker data is also taken into
183 * consideration.
184 *
185 * @param marker the marker data specific to this log statement
186 * @param format the format string
187 * @param arg1 the first argument
188 * @param arg2 the second argument
189 * @since 1.4
190 */
191 public void trace(Marker marker, String format, Object arg1, Object arg2);
192
193 /**
194 * This method is similar to {@link #trace(String, Object...)}
195 * method except that the marker data is also taken into
196 * consideration.
197 *
198 * @param marker the marker data specific to this log statement
199 * @param format the format string
200 * @param argArray an array of arguments
201 * @since 1.4
202 */
203 public void trace(Marker marker, String format, Object... argArray);
204
205 /**
206 * This method is similar to {@link #trace(String, Throwable)} method except that the
207 * marker data is also taken into consideration.
208 *
209 * @param marker the marker data specific to this log statement
210 * @param msg the message accompanying the exception
211 * @param t the exception (throwable) to log
212 * @since 1.4
213 */
214 public void trace(Marker marker, String msg, Throwable t);
215
216 /**
217 * Is the logger instance enabled for the DEBUG level?
218 *
219 * @return True if this Logger is enabled for the DEBUG level,
220 * false otherwise.
221 */
222 public boolean isDebugEnabled();
223
224 /**
225 * Log a message at the DEBUG level.
226 *
227 * @param msg the message string to be logged
228 */
229 public void debug(String msg);
230
231 /**
232 * Log a message at the DEBUG level according to the specified format
233 * and argument.
234 * <p/>
235 * <p>This form avoids superfluous object creation when the logger
236 * is disabled for the DEBUG level. </p>
237 *
238 * @param format the format string
239 * @param arg the argument
240 */
241 public void debug(String format, Object arg);
242
243 /**
244 * Log a message at the DEBUG level according to the specified format
245 * and arguments.
246 * <p/>
247 * <p>This form avoids superfluous object creation when the logger
248 * is disabled for the DEBUG level. </p>
249 *
250 * @param format the format string
251 * @param arg1 the first argument
252 * @param arg2 the second argument
253 */
254 public void debug(String format, Object arg1, Object arg2);
255
256 /**
257 * Log a message at the DEBUG level according to the specified format
258 * and arguments.
259 * <p/>
260 * <p>This form avoids superfluous string concatenation when the logger
261 * is disabled for the DEBUG level. However, this variant incurs the hidden
262 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
263 * even if this logger is disabled for DEBUG. The variants taking
264 * {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
265 * arguments exist solely in order to avoid this hidden cost.</p>
266 *
267 * @param format the format string
268 * @param arguments a list of 3 or more arguments
269 */
270 public void debug(String format, Object... arguments);
271
272 /**
273 * Log an exception (throwable) at the DEBUG level with an
274 * accompanying message.
275 *
276 * @param msg the message accompanying the exception
277 * @param t the exception (throwable) to log
278 */
279 public void debug(String msg, Throwable t);
280
281 /**
282 * Similar to {@link #isDebugEnabled()} method except that the
283 * marker data is also taken into account.
284 *
285 * @param marker The marker data to take into consideration
286 * @return True if this Logger is enabled for the DEBUG level,
287 * false otherwise.
288 */
289 public boolean isDebugEnabled(Marker marker);
290
291 /**
292 * Log a message with the specific Marker at the DEBUG level.
293 *
294 * @param marker the marker data specific to this log statement
295 * @param msg the message string to be logged
296 */
297 public void debug(Marker marker, String msg);
298
299 /**
300 * This method is similar to {@link #debug(String, Object)} method except that the
301 * marker data is also taken into consideration.
302 *
303 * @param marker the marker data specific to this log statement
304 * @param format the format string
305 * @param arg the argument
306 */
307 public void debug(Marker marker, String format, Object arg);
308
309 /**
310 * This method is similar to {@link #debug(String, Object, Object)}
311 * method except that the marker data is also taken into
312 * consideration.
313 *
314 * @param marker the marker data specific to this log statement
315 * @param format the format string
316 * @param arg1 the first argument
317 * @param arg2 the second argument
318 */
319 public void debug(Marker marker, String format, Object arg1, Object arg2);
320
321 /**
322 * This method is similar to {@link #debug(String, Object...)}
323 * method except that the marker data is also taken into
324 * consideration.
325 *
326 * @param marker the marker data specific to this log statement
327 * @param format the format string
328 * @param arguments a list of 3 or more arguments
329 */
330 public void debug(Marker marker, String format, Object... arguments);
331
332 /**
333 * This method is similar to {@link #debug(String, Throwable)} method except that the
334 * marker data is also taken into consideration.
335 *
336 * @param marker the marker data specific to this log statement
337 * @param msg the message accompanying the exception
338 * @param t the exception (throwable) to log
339 */
340 public void debug(Marker marker, String msg, Throwable t);
341
342 /**
343 * Is the logger instance enabled for the INFO level?
344 *
345 * @return True if this Logger is enabled for the INFO level,
346 * false otherwise.
347 */
348 public boolean isInfoEnabled();
349
350 /**
351 * Log a message at the INFO level.
352 *
353 * @param msg the message string to be logged
354 */
355 public void info(String msg);
356
357 /**
358 * Log a message at the INFO level according to the specified format
359 * and argument.
360 * <p/>
361 * <p>This form avoids superfluous object creation when the logger
362 * is disabled for the INFO level. </p>
363 *
364 * @param format the format string
365 * @param arg the argument
366 */
367 public void info(String format, Object arg);
368
369 /**
370 * Log a message at the INFO level according to the specified format
371 * and arguments.
372 * <p/>
373 * <p>This form avoids superfluous object creation when the logger
374 * is disabled for the INFO level. </p>
375 *
376 * @param format the format string
377 * @param arg1 the first argument
378 * @param arg2 the second argument
379 */
380 public void info(String format, Object arg1, Object arg2);
381
382 /**
383 * Log a message at the INFO level according to the specified format
384 * and arguments.
385 * <p/>
386 * <p>This form avoids superfluous string concatenation when the logger
387 * is disabled for the INFO level. However, this variant incurs the hidden
388 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
389 * even if this logger is disabled for INFO. The variants taking
390 * {@link #info(String, Object) one} and {@link #info(String, Object, Object) two}
391 * arguments exist solely in order to avoid this hidden cost.</p>
392 *
393 * @param format the format string
394 * @param arguments a list of 3 or more arguments
395 */
396 public void info(String format, Object... arguments);
397
398 /**
399 * Log an exception (throwable) at the INFO level with an
400 * accompanying message.
401 *
402 * @param msg the message accompanying the exception
403 * @param t the exception (throwable) to log
404 */
405 public void info(String msg, Throwable t);
406
407 /**
408 * Similar to {@link #isInfoEnabled()} method except that the marker
409 * data is also taken into consideration.
410 *
411 * @param marker The marker data to take into consideration
412 * @return true if this logger is warn enabled, false otherwise
413 */
414 public boolean isInfoEnabled(Marker marker);
415
416 /**
417 * Log a message with the specific Marker at the INFO level.
418 *
419 * @param marker The marker specific to this log statement
420 * @param msg the message string to be logged
421 */
422 public void info(Marker marker, String msg);
423
424 /**
425 * This method is similar to {@link #info(String, Object)} method except that the
426 * marker data is also taken into consideration.
427 *
428 * @param marker the marker data specific to this log statement
429 * @param format the format string
430 * @param arg the argument
431 */
432 public void info(Marker marker, String format, Object arg);
433
434 /**
435 * This method is similar to {@link #info(String, Object, Object)}
436 * method except that the marker data is also taken into
437 * consideration.
438 *
439 * @param marker the marker data specific to this log statement
440 * @param format the format string
441 * @param arg1 the first argument
442 * @param arg2 the second argument
443 */
444 public void info(Marker marker, String format, Object arg1, Object arg2);
445
446 /**
447 * This method is similar to {@link #info(String, Object...)}
448 * method except that the marker data is also taken into
449 * consideration.
450 *
451 * @param marker the marker data specific to this log statement
452 * @param format the format string
453 * @param arguments a list of 3 or more arguments
454 */
455 public void info(Marker marker, String format, Object... arguments);
456
457 /**
458 * This method is similar to {@link #info(String, Throwable)} method
459 * except that the marker data is also taken into consideration.
460 *
461 * @param marker the marker data for this log statement
462 * @param msg the message accompanying the exception
463 * @param t the exception (throwable) to log
464 */
465 public void info(Marker marker, String msg, Throwable t);
466
467 /**
468 * Is the logger instance enabled for the WARN level?
469 *
470 * @return True if this Logger is enabled for the WARN level,
471 * false otherwise.
472 */
473 public boolean isWarnEnabled();
474
475 /**
476 * Log a message at the WARN level.
477 *
478 * @param msg the message string to be logged
479 */
480 public void warn(String msg);
481
482 /**
483 * Log a message at the WARN level according to the specified format
484 * and argument.
485 * <p/>
486 * <p>This form avoids superfluous object creation when the logger
487 * is disabled for the WARN level. </p>
488 *
489 * @param format the format string
490 * @param arg the argument
491 */
492 public void warn(String format, Object arg);
493
494 /**
495 * Log a message at the WARN level according to the specified format
496 * and arguments.
497 * <p/>
498 * <p>This form avoids superfluous string concatenation when the logger
499 * is disabled for the WARN level. However, this variant incurs the hidden
500 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
501 * even if this logger is disabled for WARN. The variants taking
502 * {@link #warn(String, Object) one} and {@link #warn(String, Object, Object) two}
503 * arguments exist solely in order to avoid this hidden cost.</p>
504 *
505 * @param format the format string
506 * @param arguments a list of 3 or more arguments
507 */
508 public void warn(String format, Object... arguments);
509
510 /**
511 * Log a message at the WARN level according to the specified format
512 * and arguments.
513 * <p/>
514 * <p>This form avoids superfluous object creation when the logger
515 * is disabled for the WARN level. </p>
516 *
517 * @param format the format string
518 * @param arg1 the first argument
519 * @param arg2 the second argument
520 */
521 public void warn(String format, Object arg1, Object arg2);
522
523 /**
524 * Log an exception (throwable) at the WARN level with an
525 * accompanying message.
526 *
527 * @param msg the message accompanying the exception
528 * @param t the exception (throwable) to log
529 */
530 public void warn(String msg, Throwable t);
531
532 /**
533 * Similar to {@link #isWarnEnabled()} method except that the marker
534 * data is also taken into consideration.
535 *
536 * @param marker The marker data to take into consideration
537 * @return True if this Logger is enabled for the WARN level,
538 * false otherwise.
539 */
540 public boolean isWarnEnabled(Marker marker);
541
542 /**
543 * Log a message with the specific Marker at the WARN level.
544 *
545 * @param marker The marker specific to this log statement
546 * @param msg the message string to be logged
547 */
548 public void warn(Marker marker, String msg);
549
550 /**
551 * This method is similar to {@link #warn(String, Object)} method except that the
552 * marker data is also taken into consideration.
553 *
554 * @param marker the marker data specific to this log statement
555 * @param format the format string
556 * @param arg the argument
557 */
558 public void warn(Marker marker, String format, Object arg);
559
560 /**
561 * This method is similar to {@link #warn(String, Object, Object)}
562 * method except that the marker data is also taken into
563 * consideration.
564 *
565 * @param marker the marker data specific to this log statement
566 * @param format the format string
567 * @param arg1 the first argument
568 * @param arg2 the second argument
569 */
570 public void warn(Marker marker, String format, Object arg1, Object arg2);
571
572 /**
573 * This method is similar to {@link #warn(String, Object...)}
574 * method except that the marker data is also taken into
575 * consideration.
576 *
577 * @param marker the marker data specific to this log statement
578 * @param format the format string
579 * @param arguments a list of 3 or more arguments
580 */
581 public void warn(Marker marker, String format, Object... arguments);
582
583 /**
584 * This method is similar to {@link #warn(String, Throwable)} method
585 * except that the marker data is also taken into consideration.
586 *
587 * @param marker the marker data for this log statement
588 * @param msg the message accompanying the exception
589 * @param t the exception (throwable) to log
590 */
591 public void warn(Marker marker, String msg, Throwable t);
592
593 /**
594 * Is the logger instance enabled for the ERROR level?
595 *
596 * @return True if this Logger is enabled for the ERROR level,
597 * false otherwise.
598 */
599 public boolean isErrorEnabled();
600
601 /**
602 * Log a message at the ERROR level.
603 *
604 * @param msg the message string to be logged
605 */
606 public void error(String msg);
607
608 /**
609 * Log a message at the ERROR level according to the specified format
610 * and argument.
611 * <p/>
612 * <p>This form avoids superfluous object creation when the logger
613 * is disabled for the ERROR level. </p>
614 *
615 * @param format the format string
616 * @param arg the argument
617 */
618 public void error(String format, Object arg);
619
620 /**
621 * Log a message at the ERROR level according to the specified format
622 * and arguments.
623 * <p/>
624 * <p>This form avoids superfluous object creation when the logger
625 * is disabled for the ERROR level. </p>
626 *
627 * @param format the format string
628 * @param arg1 the first argument
629 * @param arg2 the second argument
630 */
631 public void error(String format, Object arg1, Object arg2);
632
633 /**
634 * Log a message at the ERROR level according to the specified format
635 * and arguments.
636 * <p/>
637 * <p>This form avoids superfluous string concatenation when the logger
638 * is disabled for the ERROR level. However, this variant incurs the hidden
639 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
640 * even if this logger is disabled for ERROR. The variants taking
641 * {@link #error(String, Object) one} and {@link #error(String, Object, Object) two}
642 * arguments exist solely in order to avoid this hidden cost.</p>
643 *
644 * @param format the format string
645 * @param arguments a list of 3 or more arguments
646 */
647 public void error(String format, Object... arguments);
648
649 /**
650 * Log an exception (throwable) at the ERROR level with an
651 * accompanying message.
652 *
653 * @param msg the message accompanying the exception
654 * @param t the exception (throwable) to log
655 */
656 public void error(String msg, Throwable t);
657
658 /**
659 * Similar to {@link #isErrorEnabled()} method except that the
660 * marker data is also taken into consideration.
661 *
662 * @param marker The marker data to take into consideration
663 * @return True if this Logger is enabled for the ERROR level,
664 * false otherwise.
665 */
666 public boolean isErrorEnabled(Marker marker);
667
668 /**
669 * Log a message with the specific Marker at the ERROR level.
670 *
671 * @param marker The marker specific to this log statement
672 * @param msg the message string to be logged
673 */
674 public void error(Marker marker, String msg);
675
676 /**
677 * This method is similar to {@link #error(String, Object)} method except that the
678 * marker data is also taken into consideration.
679 *
680 * @param marker the marker data specific to this log statement
681 * @param format the format string
682 * @param arg the argument
683 */
684 public void error(Marker marker, String format, Object arg);
685
686 /**
687 * This method is similar to {@link #error(String, Object, Object)}
688 * method except that the marker data is also taken into
689 * consideration.
690 *
691 * @param marker the marker data specific to this log statement
692 * @param format the format string
693 * @param arg1 the first argument
694 * @param arg2 the second argument
695 */
696 public void error(Marker marker, String format, Object arg1, Object arg2);
697
698 /**
699 * This method is similar to {@link #error(String, Object...)}
700 * method except that the marker data is also taken into
701 * consideration.
702 *
703 * @param marker the marker data specific to this log statement
704 * @param format the format string
705 * @param arguments a list of 3 or more arguments
706 */
707 public void error(Marker marker, String format, Object... arguments);
708
709 /**
710 * This method is similar to {@link #error(String, Throwable)}
711 * method except that the marker data is also taken into
712 * consideration.
713 *
714 * @param marker the marker data specific to this log statement
715 * @param msg the message accompanying the exception
716 * @param t the exception (throwable) to log
717 */
718 public void error(Marker marker, String msg, Throwable t);
719
720 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.IOException;
27 import java.net.URL;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Enumeration;
31 import java.util.LinkedHashSet;
32 import java.util.List;
33 import java.util.Set;
34 import java.util.concurrent.LinkedBlockingQueue;
35
36 import org.slf4j.event.SubstituteLoggingEvent;
37 import org.slf4j.helpers.NOPLoggerFactory;
38 import org.slf4j.helpers.SubstituteLogger;
39 import org.slf4j.helpers.SubstituteLoggerFactory;
40 import org.slf4j.helpers.Util;
41 import org.slf4j.impl.StaticLoggerBinder;
42
43 /**
44 * The <code>LoggerFactory</code> is a utility class producing Loggers for
45 * various logging APIs, most notably for log4j, logback and JDK 1.4 logging.
46 * Other implementations such as {@link org.slf4j.impl.NOPLogger NOPLogger} and
47 * {@link org.slf4j.impl.SimpleLogger SimpleLogger} are also supported.
48 * <p/>
49 * <p/>
50 * <code>LoggerFactory</code> is essentially a wrapper around an
51 * {@link ILoggerFactory} instance bound with <code>LoggerFactory</code> at
52 * compile time.
53 * <p/>
54 * <p/>
55 * Please note that all methods in <code>LoggerFactory</code> are static.
56 *
57 *
58 * @author Alexander Dorokhine
59 * @author Robert Elliot
60 * @author Ceki G&uuml;lc&uuml;
61 *
62 */
63 public final class LoggerFactory {
64
65 static final String CODES_PREFIX = "http://www.slf4j.org/codes.html";
66
67 static final String NO_STATICLOGGERBINDER_URL = CODES_PREFIX + "#StaticLoggerBinder";
68 static final String MULTIPLE_BINDINGS_URL = CODES_PREFIX + "#multiple_bindings";
69 static final String NULL_LF_URL = CODES_PREFIX + "#null_LF";
70 static final String VERSION_MISMATCH = CODES_PREFIX + "#version_mismatch";
71 static final String SUBSTITUTE_LOGGER_URL = CODES_PREFIX + "#substituteLogger";
72 static final String LOGGER_NAME_MISMATCH_URL = CODES_PREFIX + "#loggerNameMismatch";
73 static final String REPLAY_URL = CODES_PREFIX + "#replay";
74
75 static final String UNSUCCESSFUL_INIT_URL = CODES_PREFIX + "#unsuccessfulInit";
76 static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory in failed state. Original exception was thrown EARLIER. See also " + UNSUCCESSFUL_INIT_URL;
77
78 static final int UNINITIALIZED = 0;
79 static final int ONGOING_INITIALIZATION = 1;
80 static final int FAILED_INITIALIZATION = 2;
81 static final int SUCCESSFUL_INITIALIZATION = 3;
82 static final int NOP_FALLBACK_INITIALIZATION = 4;
83
84 static volatile int INITIALIZATION_STATE = UNINITIALIZED;
85 static final SubstituteLoggerFactory SUBST_FACTORY = new SubstituteLoggerFactory();
86 static final NOPLoggerFactory NOP_FALLBACK_FACTORY = new NOPLoggerFactory();
87
88 // Support for detecting mismatched logger names.
89 static final String DETECT_LOGGER_NAME_MISMATCH_PROPERTY = "slf4j.detectLoggerNameMismatch";
90 static final String JAVA_VENDOR_PROPERTY = "java.vendor.url";
91
92 static boolean DETECT_LOGGER_NAME_MISMATCH = Util.safeGetBooleanSystemProperty(DETECT_LOGGER_NAME_MISMATCH_PROPERTY);
93
94 /**
95 * It is LoggerFactory's responsibility to track version changes and manage
96 * the compatibility list.
97 * <p/>
98 * <p/>
99 * It is assumed that all versions in the 1.6 are mutually compatible.
100 */
101 static private final String[] API_COMPATIBILITY_LIST = new String[] { "1.6", "1.7" };
102
103 // private constructor prevents instantiation
104 private LoggerFactory() {
105 }
106
107 /**
108 * Force LoggerFactory to consider itself uninitialized.
109 * <p/>
110 * <p/>
111 * This method is intended to be called by classes (in the same package) for
112 * testing purposes. This method is internal. It can be modified, renamed or
113 * removed at any time without notice.
114 * <p/>
115 * <p/>
116 * You are strongly discouraged from calling this method in production code.
117 */
118 static void reset() {
119 INITIALIZATION_STATE = UNINITIALIZED;
120 }
121
122 private final static void performInitialization() {
123 bind();
124 if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
125 versionSanityCheck();
126 }
127 }
128
129 private static boolean messageContainsOrgSlf4jImplStaticLoggerBinder(String msg) {
130 if (msg == null)
131 return false;
132 if (msg.contains("org/slf4j/impl/StaticLoggerBinder"))
133 return true;
134 if (msg.contains("org.slf4j.impl.StaticLoggerBinder"))
135 return true;
136 return false;
137 }
138
139 private final static void bind() {
140 try {
141 Set<URL> staticLoggerBinderPathSet = null;
142 // skip check under android, see also
143 // http://jira.qos.ch/browse/SLF4J-328
144 if (!isAndroid()) {
145 staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
146 reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
147 }
148 // the next line does the binding
149 StaticLoggerBinder.getSingleton();
150 INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
151 reportActualBinding(staticLoggerBinderPathSet);
152 fixSubstituteLoggers();
153 replayEvents();
154 // release all resources in SUBST_FACTORY
155 SUBST_FACTORY.clear();
156 } catch (NoClassDefFoundError ncde) {
157 String msg = ncde.getMessage();
158 if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) {
159 INITIALIZATION_STATE = NOP_FALLBACK_INITIALIZATION;
160 Util.report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
161 Util.report("Defaulting to no-operation (NOP) logger implementation");
162 Util.report("See " + NO_STATICLOGGERBINDER_URL + " for further details.");
163 } else {
164 failedBinding(ncde);
165 throw ncde;
166 }
167 } catch (java.lang.NoSuchMethodError nsme) {
168 String msg = nsme.getMessage();
169 if (msg != null && msg.contains("org.slf4j.impl.StaticLoggerBinder.getSingleton()")) {
170 INITIALIZATION_STATE = FAILED_INITIALIZATION;
171 Util.report("slf4j-api 1.6.x (or later) is incompatible with this binding.");
172 Util.report("Your binding is version 1.5.5 or earlier.");
173 Util.report("Upgrade your binding to version 1.6.x.");
174 }
175 throw nsme;
176 } catch (Exception e) {
177 failedBinding(e);
178 throw new IllegalStateException("Unexpected initialization failure", e);
179 }
180 }
181
182 private static void fixSubstituteLoggers() {
183 synchronized (SUBST_FACTORY) {
184 SUBST_FACTORY.postInitialization();
185 for (SubstituteLogger substLogger : SUBST_FACTORY.getLoggers()) {
186 Logger logger = getLogger(substLogger.getName());
187 substLogger.setDelegate(logger);
188 }
189 }
190
191 }
192
193 static void failedBinding(Throwable t) {
194 INITIALIZATION_STATE = FAILED_INITIALIZATION;
195 Util.report("Failed to instantiate SLF4J LoggerFactory", t);
196 }
197
198 private static void replayEvents() {
199 final LinkedBlockingQueue<SubstituteLoggingEvent> queue = SUBST_FACTORY.getEventQueue();
200 final int queueSize = queue.size();
201 int count = 0;
202 final int maxDrain = 128;
203 List<SubstituteLoggingEvent> eventList = new ArrayList<SubstituteLoggingEvent>(maxDrain);
204 while (true) {
205 int numDrained = queue.drainTo(eventList, maxDrain);
206 if (numDrained == 0)
207 break;
208 for (SubstituteLoggingEvent event : eventList) {
209 replaySingleEvent(event);
210 if (count++ == 0)
211 emitReplayOrSubstituionWarning(event, queueSize);
212 }
213 eventList.clear();
214 }
215 }
216
217 private static void emitReplayOrSubstituionWarning(SubstituteLoggingEvent event, int queueSize) {
218 if (event.getLogger().isDelegateEventAware()) {
219 emitReplayWarning(queueSize);
220 } else if (event.getLogger().isDelegateNOP()) {
221 // nothing to do
222 } else {
223 emitSubstitutionWarning();
224 }
225 }
226
227 private static void replaySingleEvent(SubstituteLoggingEvent event) {
228 if (event == null)
229 return;
230
231 SubstituteLogger substLogger = event.getLogger();
232 String loggerName = substLogger.getName();
233 if (substLogger.isDelegateNull()) {
234 throw new IllegalStateException("Delegate logger cannot be null at this state.");
235 }
236
237 if (substLogger.isDelegateNOP()) {
238 // nothing to do
239 } else if (substLogger.isDelegateEventAware()) {
240 substLogger.log(event);
241 } else {
242 Util.report(loggerName);
243 }
244 }
245
246 private static void emitSubstitutionWarning() {
247 Util.report("The following set of substitute loggers may have been accessed");
248 Util.report("during the initialization phase. Logging calls during this");
249 Util.report("phase were not honored. However, subsequent logging calls to these");
250 Util.report("loggers will work as normally expected.");
251 Util.report("See also " + SUBSTITUTE_LOGGER_URL);
252 }
253
254 private static void emitReplayWarning(int eventCount) {
255 Util.report("A number (" + eventCount + ") of logging calls during the initialization phase have been intercepted and are");
256 Util.report("now being replayed. These are subject to the filtering rules of the underlying logging system.");
257 Util.report("See also " + REPLAY_URL);
258 }
259
260 private final static void versionSanityCheck() {
261 try {
262 String requested = StaticLoggerBinder.REQUESTED_API_VERSION;
263
264 boolean match = false;
265 for (String aAPI_COMPATIBILITY_LIST : API_COMPATIBILITY_LIST) {
266 if (requested.startsWith(aAPI_COMPATIBILITY_LIST)) {
267 match = true;
268 }
269 }
270 if (!match) {
271 Util.report("The requested version " + requested + " by your slf4j binding is not compatible with "
272 + Arrays.asList(API_COMPATIBILITY_LIST).toString());
273 Util.report("See " + VERSION_MISMATCH + " for further details.");
274 }
275 } catch (java.lang.NoSuchFieldError nsfe) {
276 // given our large user base and SLF4J's commitment to backward
277 // compatibility, we cannot cry here. Only for implementations
278 // which willingly declare a REQUESTED_API_VERSION field do we
279 // emit compatibility warnings.
280 } catch (Throwable e) {
281 // we should never reach here
282 Util.report("Unexpected problem occured during version sanity check", e);
283 }
284 }
285
286 // We need to use the name of the StaticLoggerBinder class, but we can't
287 // reference
288 // the class itself.
289 private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class";
290
291 static Set<URL> findPossibleStaticLoggerBinderPathSet() {
292 // use Set instead of list in order to deal with bug #138
293 // LinkedHashSet appropriate here because it preserves insertion order
294 // during iteration
295 Set<URL> staticLoggerBinderPathSet = new LinkedHashSet<URL>();
296 try {
297 ClassLoader loggerFactoryClassLoader = LoggerFactory.class.getClassLoader();
298 Enumeration<URL> paths;
299 if (loggerFactoryClassLoader == null) {
300 paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);
301 } else {
302 paths = loggerFactoryClassLoader.getResources(STATIC_LOGGER_BINDER_PATH);
303 }
304 while (paths.hasMoreElements()) {
305 URL path = paths.nextElement();
306 staticLoggerBinderPathSet.add(path);
307 }
308 } catch (IOException ioe) {
309 Util.report("Error getting resources from path", ioe);
310 }
311 return staticLoggerBinderPathSet;
312 }
313
314 private static boolean isAmbiguousStaticLoggerBinderPathSet(Set<URL> binderPathSet) {
315 return binderPathSet.size() > 1;
316 }
317
318 /**
319 * Prints a warning message on the console if multiple bindings were found
320 * on the class path. No reporting is done otherwise.
321 *
322 */
323 private static void reportMultipleBindingAmbiguity(Set<URL> binderPathSet) {
324 if (isAmbiguousStaticLoggerBinderPathSet(binderPathSet)) {
325 Util.report("Class path contains multiple SLF4J bindings.");
326 for (URL path : binderPathSet) {
327 Util.report("Found binding in [" + path + "]");
328 }
329 Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation.");
330 }
331 }
332
333 private static boolean isAndroid() {
334 String vendor = Util.safeGetSystemProperty(JAVA_VENDOR_PROPERTY);
335 if (vendor == null)
336 return false;
337 return vendor.toLowerCase().contains("android");
338 }
339
340 private static void reportActualBinding(Set<URL> binderPathSet) {
341 // binderPathSet can be null under Android
342 if (binderPathSet != null && isAmbiguousStaticLoggerBinderPathSet(binderPathSet)) {
343 Util.report("Actual binding is of type [" + StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr() + "]");
344 }
345 }
346
347 /**
348 * Return a logger named according to the name parameter using the
349 * statically bound {@link ILoggerFactory} instance.
350 *
351 * @param name
352 * The name of the logger.
353 * @return logger
354 */
355 public static Logger getLogger(String name) {
356 ILoggerFactory iLoggerFactory = getILoggerFactory();
357 return iLoggerFactory.getLogger(name);
358 }
359
360 /**
361 * Return a logger named corresponding to the class passed as parameter,
362 * using the statically bound {@link ILoggerFactory} instance.
363 *
364 * <p>
365 * In case the the <code>clazz</code> parameter differs from the name of the
366 * caller as computed internally by SLF4J, a logger name mismatch warning
367 * will be printed but only if the
368 * <code>slf4j.detectLoggerNameMismatch</code> system property is set to
369 * true. By default, this property is not set and no warnings will be
370 * printed even in case of a logger name mismatch.
371 *
372 * @param clazz
373 * the returned logger will be named after clazz
374 * @return logger
375 *
376 *
377 * @see <a
378 * href="http://www.slf4j.org/codes.html#loggerNameMismatch">Detected
379 * logger name mismatch</a>
380 */
381 public static Logger getLogger(Class<?> clazz) {
382 Logger logger = getLogger(clazz.getName());
383 if (DETECT_LOGGER_NAME_MISMATCH) {
384 Class<?> autoComputedCallingClass = Util.getCallingClass();
385 if (autoComputedCallingClass != null && nonMatchingClasses(clazz, autoComputedCallingClass)) {
386 Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(),
387 autoComputedCallingClass.getName()));
388 Util.report("See " + LOGGER_NAME_MISMATCH_URL + " for an explanation");
389 }
390 }
391 return logger;
392 }
393
394 private static boolean nonMatchingClasses(Class<?> clazz, Class<?> autoComputedCallingClass) {
395 return !autoComputedCallingClass.isAssignableFrom(clazz);
396 }
397
398 /**
399 * Return the {@link ILoggerFactory} instance in use.
400 * <p/>
401 * <p/>
402 * ILoggerFactory instance is bound with this class at compile time.
403 *
404 * @return the ILoggerFactory instance in use
405 */
406 public static ILoggerFactory getILoggerFactory() {
407 if (INITIALIZATION_STATE == UNINITIALIZED) {
408 synchronized (LoggerFactory.class) {
409 if (INITIALIZATION_STATE == UNINITIALIZED) {
410 INITIALIZATION_STATE = ONGOING_INITIALIZATION;
411 performInitialization();
412 }
413 }
414 }
415 switch (INITIALIZATION_STATE) {
416 case SUCCESSFUL_INITIALIZATION:
417 return StaticLoggerBinder.getSingleton().getLoggerFactory();
418 case NOP_FALLBACK_INITIALIZATION:
419 return NOP_FALLBACK_FACTORY;
420 case FAILED_INITIALIZATION:
421 throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
422 case ONGOING_INITIALIZATION:
423 // support re-entrant behavior.
424 // See also http://jira.qos.ch/browse/SLF4J-97
425 return SUBST_FACTORY;
426 }
427 throw new IllegalStateException("Unreachable code");
428 }
429 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.IOException;
27 import java.net.URL;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Enumeration;
31 import java.util.LinkedHashSet;
32 import java.util.List;
33 import java.util.Set;
34 import java.util.concurrent.LinkedBlockingQueue;
35
36 import org.slf4j.event.SubstituteLoggingEvent;
37 import org.slf4j.helpers.NOPLoggerFactory;
38 import org.slf4j.helpers.SubstituteLogger;
39 import org.slf4j.helpers.SubstituteLoggerFactory;
40 import org.slf4j.helpers.Util;
41 import org.slf4j.impl.StaticLoggerBinder;
42
43 /**
44 * The <code>LoggerFactory</code> is a utility class producing Loggers for
45 * various logging APIs, most notably for log4j, logback and JDK 1.4 logging.
46 * Other implementations such as {@link org.slf4j.impl.NOPLogger NOPLogger} and
47 * {@link org.slf4j.impl.SimpleLogger SimpleLogger} are also supported.
48 * <p/>
49 * <p/>
50 * <code>LoggerFactory</code> is essentially a wrapper around an
51 * {@link ILoggerFactory} instance bound with <code>LoggerFactory</code> at
52 * compile time.
53 * <p/>
54 * <p/>
55 * Please note that all methods in <code>LoggerFactory</code> are static.
56 *
57 *
58 * @author Alexander Dorokhine
59 * @author Robert Elliot
60 * @author Ceki G&uuml;lc&uuml;
61 *
62 */
63 public final class LoggerFactory {
64
65 static final String CODES_PREFIX = "http://www.slf4j.org/codes.html";
66
67 static final String NO_STATICLOGGERBINDER_URL = CODES_PREFIX + "#StaticLoggerBinder";
68 static final String MULTIPLE_BINDINGS_URL = CODES_PREFIX + "#multiple_bindings";
69 static final String NULL_LF_URL = CODES_PREFIX + "#null_LF";
70 static final String VERSION_MISMATCH = CODES_PREFIX + "#version_mismatch";
71 static final String SUBSTITUTE_LOGGER_URL = CODES_PREFIX + "#substituteLogger";
72 static final String LOGGER_NAME_MISMATCH_URL = CODES_PREFIX + "#loggerNameMismatch";
73 static final String REPLAY_URL = CODES_PREFIX + "#replay";
74
75 static final String UNSUCCESSFUL_INIT_URL = CODES_PREFIX + "#unsuccessfulInit";
76 static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory in failed state. Original exception was thrown EARLIER. See also " + UNSUCCESSFUL_INIT_URL;
77
78 static final int UNINITIALIZED = 0;
79 static final int ONGOING_INITIALIZATION = 1;
80 static final int FAILED_INITIALIZATION = 2;
81 static final int SUCCESSFUL_INITIALIZATION = 3;
82 static final int NOP_FALLBACK_INITIALIZATION = 4;
83
84 static volatile int INITIALIZATION_STATE = UNINITIALIZED;
85 static final SubstituteLoggerFactory SUBST_FACTORY = new SubstituteLoggerFactory();
86 static final NOPLoggerFactory NOP_FALLBACK_FACTORY = new NOPLoggerFactory();
87
88 // Support for detecting mismatched logger names.
89 static final String DETECT_LOGGER_NAME_MISMATCH_PROPERTY = "slf4j.detectLoggerNameMismatch";
90 static final String JAVA_VENDOR_PROPERTY = "java.vendor.url";
91
92 static boolean DETECT_LOGGER_NAME_MISMATCH = Util.safeGetBooleanSystemProperty(DETECT_LOGGER_NAME_MISMATCH_PROPERTY);
93
94 /**
95 * It is LoggerFactory's responsibility to track version changes and manage
96 * the compatibility list.
97 * <p/>
98 * <p/>
99 * It is assumed that all versions in the 1.6 are mutually compatible.
100 */
101 static private final String[] API_COMPATIBILITY_LIST = new String[] { "1.6", "1.7" };
102
103 // private constructor prevents instantiation
104 private LoggerFactory() {
105 }
106
107 /**
108 * Force LoggerFactory to consider itself uninitialized.
109 * <p/>
110 * <p/>
111 * This method is intended to be called by classes (in the same package) for
112 * testing purposes. This method is internal. It can be modified, renamed or
113 * removed at any time without notice.
114 * <p/>
115 * <p/>
116 * You are strongly discouraged from calling this method in production code.
117 */
118 static void reset() {
119 INITIALIZATION_STATE = UNINITIALIZED;
120 }
121
122 private final static void performInitialization() {
123 bind();
124 if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
125 versionSanityCheck();
126 }
127 }
128
129 private static boolean messageContainsOrgSlf4jImplStaticLoggerBinder(String msg) {
130 if (msg == null)
131 return false;
132 if (msg.contains("org/slf4j/impl/StaticLoggerBinder"))
133 return true;
134 if (msg.contains("org.slf4j.impl.StaticLoggerBinder"))
135 return true;
136 return false;
137 }
138
139 private final static void bind() {
140 try {
141 Set<URL> staticLoggerBinderPathSet = null;
142 // skip check under android, see also
143 // http://jira.qos.ch/browse/SLF4J-328
144 if (!isAndroid()) {
145 staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
146 reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
147 }
148 // the next line does the binding
149 StaticLoggerBinder.getSingleton();
150 INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
151 reportActualBinding(staticLoggerBinderPathSet);
152 fixSubstituteLoggers();
153 replayEvents();
154 // release all resources in SUBST_FACTORY
155 SUBST_FACTORY.clear();
156 } catch (NoClassDefFoundError ncde) {
157 String msg = ncde.getMessage();
158 if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) {
159 INITIALIZATION_STATE = NOP_FALLBACK_INITIALIZATION;
160 Util.report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
161 Util.report("Defaulting to no-operation (NOP) logger implementation");
162 Util.report("See " + NO_STATICLOGGERBINDER_URL + " for further details.");
163 } else {
164 failedBinding(ncde);
165 throw ncde;
166 }
167 } catch (java.lang.NoSuchMethodError nsme) {
168 String msg = nsme.getMessage();
169 if (msg != null && msg.contains("org.slf4j.impl.StaticLoggerBinder.getSingleton()")) {
170 INITIALIZATION_STATE = FAILED_INITIALIZATION;
171 Util.report("slf4j-api 1.6.x (or later) is incompatible with this binding.");
172 Util.report("Your binding is version 1.5.5 or earlier.");
173 Util.report("Upgrade your binding to version 1.6.x.");
174 }
175 throw nsme;
176 } catch (Exception e) {
177 failedBinding(e);
178 throw new IllegalStateException("Unexpected initialization failure", e);
179 }
180 }
181
182 private static void fixSubstituteLoggers() {
183 synchronized (SUBST_FACTORY) {
184 SUBST_FACTORY.postInitialization();
185 for (SubstituteLogger substLogger : SUBST_FACTORY.getLoggers()) {
186 Logger logger = getLogger(substLogger.getName());
187 substLogger.setDelegate(logger);
188 }
189 }
190
191 }
192
193 static void failedBinding(Throwable t) {
194 INITIALIZATION_STATE = FAILED_INITIALIZATION;
195 Util.report("Failed to instantiate SLF4J LoggerFactory", t);
196 }
197
198 private static void replayEvents() {
199 final LinkedBlockingQueue<SubstituteLoggingEvent> queue = SUBST_FACTORY.getEventQueue();
200 final int queueSize = queue.size();
201 int count = 0;
202 final int maxDrain = 128;
203 List<SubstituteLoggingEvent> eventList = new ArrayList<SubstituteLoggingEvent>(maxDrain);
204 while (true) {
205 int numDrained = queue.drainTo(eventList, maxDrain);
206 if (numDrained == 0)
207 break;
208 for (SubstituteLoggingEvent event : eventList) {
209 replaySingleEvent(event);
210 if (count++ == 0)
211 emitReplayOrSubstituionWarning(event, queueSize);
212 }
213 eventList.clear();
214 }
215 }
216
217 private static void emitReplayOrSubstituionWarning(SubstituteLoggingEvent event, int queueSize) {
218 if (event.getLogger().isDelegateEventAware()) {
219 emitReplayWarning(queueSize);
220 } else if (event.getLogger().isDelegateNOP()) {
221 // nothing to do
222 } else {
223 emitSubstitutionWarning();
224 }
225 }
226
227 private static void replaySingleEvent(SubstituteLoggingEvent event) {
228 if (event == null)
229 return;
230
231 SubstituteLogger substLogger = event.getLogger();
232 String loggerName = substLogger.getName();
233 if (substLogger.isDelegateNull()) {
234 throw new IllegalStateException("Delegate logger cannot be null at this state.");
235 }
236
237 if (substLogger.isDelegateNOP()) {
238 // nothing to do
239 } else if (substLogger.isDelegateEventAware()) {
240 substLogger.log(event);
241 } else {
242 Util.report(loggerName);
243 }
244 }
245
246 private static void emitSubstitutionWarning() {
247 Util.report("The following set of substitute loggers may have been accessed");
248 Util.report("during the initialization phase. Logging calls during this");
249 Util.report("phase were not honored. However, subsequent logging calls to these");
250 Util.report("loggers will work as normally expected.");
251 Util.report("See also " + SUBSTITUTE_LOGGER_URL);
252 }
253
254 private static void emitReplayWarning(int eventCount) {
255 Util.report("A number (" + eventCount + ") of logging calls during the initialization phase have been intercepted and are");
256 Util.report("now being replayed. These are subject to the filtering rules of the underlying logging system.");
257 Util.report("See also " + REPLAY_URL);
258 }
259
260 private final static void versionSanityCheck() {
261 try {
262 String requested = StaticLoggerBinder.REQUESTED_API_VERSION;
263
264 boolean match = false;
265 for (String aAPI_COMPATIBILITY_LIST : API_COMPATIBILITY_LIST) {
266 if (requested.startsWith(aAPI_COMPATIBILITY_LIST)) {
267 match = true;
268 }
269 }
270 if (!match) {
271 Util.report("The requested version " + requested + " by your slf4j binding is not compatible with "
272 + Arrays.asList(API_COMPATIBILITY_LIST).toString());
273 Util.report("See " + VERSION_MISMATCH + " for further details.");
274 }
275 } catch (java.lang.NoSuchFieldError nsfe) {
276 // given our large user base and SLF4J's commitment to backward
277 // compatibility, we cannot cry here. Only for implementations
278 // which willingly declare a REQUESTED_API_VERSION field do we
279 // emit compatibility warnings.
280 } catch (Throwable e) {
281 // we should never reach here
282 Util.report("Unexpected problem occured during version sanity check", e);
283 }
284 }
285
286 // We need to use the name of the StaticLoggerBinder class, but we can't
287 // reference
288 // the class itself.
289 private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class";
290
291 static Set<URL> findPossibleStaticLoggerBinderPathSet() {
292 // use Set instead of list in order to deal with bug #138
293 // LinkedHashSet appropriate here because it preserves insertion order
294 // during iteration
295 Set<URL> staticLoggerBinderPathSet = new LinkedHashSet<URL>();
296 try {
297 ClassLoader loggerFactoryClassLoader = LoggerFactory.class.getClassLoader();
298 Enumeration<URL> paths;
299 if (loggerFactoryClassLoader == null) {
300 paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);
301 } else {
302 paths = loggerFactoryClassLoader.getResources(STATIC_LOGGER_BINDER_PATH);
303 }
304 while (paths.hasMoreElements()) {
305 URL path = paths.nextElement();
306 staticLoggerBinderPathSet.add(path);
307 }
308 } catch (IOException ioe) {
309 Util.report("Error getting resources from path", ioe);
310 }
311 return staticLoggerBinderPathSet;
312 }
313
314 private static boolean isAmbiguousStaticLoggerBinderPathSet(Set<URL> binderPathSet) {
315 return binderPathSet.size() > 1;
316 }
317
318 /**
319 * Prints a warning message on the console if multiple bindings were found
320 * on the class path. No reporting is done otherwise.
321 *
322 */
323 private static void reportMultipleBindingAmbiguity(Set<URL> binderPathSet) {
324 if (isAmbiguousStaticLoggerBinderPathSet(binderPathSet)) {
325 Util.report("Class path contains multiple SLF4J bindings.");
326 for (URL path : binderPathSet) {
327 Util.report("Found binding in [" + path + "]");
328 }
329 Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation.");
330 }
331 }
332
333 private static boolean isAndroid() {
334 String vendor = Util.safeGetSystemProperty(JAVA_VENDOR_PROPERTY);
335 if (vendor == null)
336 return false;
337 return vendor.toLowerCase().contains("android");
338 }
339
340 private static void reportActualBinding(Set<URL> binderPathSet) {
341 // binderPathSet can be null under Android
342 if (binderPathSet != null && isAmbiguousStaticLoggerBinderPathSet(binderPathSet)) {
343 Util.report("Actual binding is of type [" + StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr() + "]");
344 }
345 }
346
347 /**
348 * Return a logger named according to the name parameter using the
349 * statically bound {@link ILoggerFactory} instance.
350 *
351 * @param name
352 * The name of the logger.
353 * @return logger
354 */
355 public static Logger getLogger(String name) {
356 ILoggerFactory iLoggerFactory = getILoggerFactory();
357 return iLoggerFactory.getLogger(name);
358 }
359
360 /**
361 * Return a logger named corresponding to the class passed as parameter,
362 * using the statically bound {@link ILoggerFactory} instance.
363 *
364 * <p>
365 * In case the the <code>clazz</code> parameter differs from the name of the
366 * caller as computed internally by SLF4J, a logger name mismatch warning
367 * will be printed but only if the
368 * <code>slf4j.detectLoggerNameMismatch</code> system property is set to
369 * true. By default, this property is not set and no warnings will be
370 * printed even in case of a logger name mismatch.
371 *
372 * @param clazz
373 * the returned logger will be named after clazz
374 * @return logger
375 *
376 *
377 * @see <a
378 * href="http://www.slf4j.org/codes.html#loggerNameMismatch">Detected
379 * logger name mismatch</a>
380 */
381 public static Logger getLogger(Class<?> clazz) {
382 Logger logger = getLogger(clazz.getName());
383 if (DETECT_LOGGER_NAME_MISMATCH) {
384 Class<?> autoComputedCallingClass = Util.getCallingClass();
385 if (autoComputedCallingClass != null && nonMatchingClasses(clazz, autoComputedCallingClass)) {
386 Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(),
387 autoComputedCallingClass.getName()));
388 Util.report("See " + LOGGER_NAME_MISMATCH_URL + " for an explanation");
389 }
390 }
391 return logger;
392 }
393
394 private static boolean nonMatchingClasses(Class<?> clazz, Class<?> autoComputedCallingClass) {
395 return !autoComputedCallingClass.isAssignableFrom(clazz);
396 }
397
398 /**
399 * Return the {@link ILoggerFactory} instance in use.
400 * <p/>
401 * <p/>
402 * ILoggerFactory instance is bound with this class at compile time.
403 *
404 * @return the ILoggerFactory instance in use
405 */
406 public static ILoggerFactory getILoggerFactory() {
407 if (INITIALIZATION_STATE == UNINITIALIZED) {
408 synchronized (LoggerFactory.class) {
409 if (INITIALIZATION_STATE == UNINITIALIZED) {
410 INITIALIZATION_STATE = ONGOING_INITIALIZATION;
411 performInitialization();
412 }
413 }
414 }
415 switch (INITIALIZATION_STATE) {
416 case SUCCESSFUL_INITIALIZATION:
417 return StaticLoggerBinder.getSingleton().getLoggerFactory();
418 case NOP_FALLBACK_INITIALIZATION:
419 return NOP_FALLBACK_FACTORY;
420 case FAILED_INITIALIZATION:
421 throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
422 case ONGOING_INITIALIZATION:
423 // support re-entrant behavior.
424 // See also http://jira.qos.ch/browse/SLF4J-97
425 return SUBST_FACTORY;
426 }
427 throw new IllegalStateException("Unreachable code");
428 }
429 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.Closeable;
27 import java.util.Map;
28
29 import org.slf4j.helpers.NOPMDCAdapter;
30 import org.slf4j.helpers.BasicMDCAdapter;
31 import org.slf4j.helpers.Util;
32 import org.slf4j.impl.StaticMDCBinder;
33 import org.slf4j.spi.MDCAdapter;
34
35 /**
36 * This class hides and serves as a substitute for the underlying logging
37 * system's MDC implementation.
38 *
39 * <p>
40 * If the underlying logging system offers MDC functionality, then SLF4J's MDC,
41 * i.e. this class, will delegate to the underlying system's MDC. Note that at
42 * this time, only two logging systems, namely log4j and logback, offer MDC
43 * functionality. For java.util.logging which does not support MDC,
44 * {@link BasicMDCAdapter} will be used. For other systems, i.e. slf4j-simple
45 * and slf4j-nop, {@link NOPMDCAdapter} will be used.
46 *
47 * <p>
48 * Thus, as a SLF4J user, you can take advantage of MDC in the presence of log4j,
49 * logback, or java.util.logging, but without forcing these systems as
50 * dependencies upon your users.
51 *
52 * <p>
53 * For more information on MDC please see the <a
54 * href="http://logback.qos.ch/manual/mdc.html">chapter on MDC</a> in the
55 * logback manual.
56 *
57 * <p>
58 * Please note that all methods in this class are static.
59 *
60 * @author Ceki G&uuml;lc&uuml;
61 * @since 1.4.1
62 */
63 public class MDC {
64
65 static final String NULL_MDCA_URL = "http://www.slf4j.org/codes.html#null_MDCA";
66 static final String NO_STATIC_MDC_BINDER_URL = "http://www.slf4j.org/codes.html#no_static_mdc_binder";
67 static MDCAdapter mdcAdapter;
68
69 /**
70 * An adapter to remove the key when done.
71 */
72 public static class MDCCloseable implements Closeable {
73 private final String key;
74
75 private MDCCloseable(String key) {
76 this.key = key;
77 }
78
79 public void close() {
80 MDC.remove(this.key);
81 }
82 }
83
84 private MDC() {
85 }
86
87 /**
88 * As of SLF4J version 1.7.14, StaticMDCBinder classes shipping in various bindings
89 * come with a getSingleton() method. Previously only a public field called SINGLETON
90 * was available.
91 *
92 * @return MDCAdapter
93 * @throws NoClassDefFoundError in case no binding is available
94 * @since 1.7.14
95 */
96 private static MDCAdapter bwCompatibleGetMDCAdapterFromBinder() throws NoClassDefFoundError {
97 try {
98 return StaticMDCBinder.getSingleton().getMDCA();
99 } catch (NoSuchMethodError nsme) {
100 // binding is probably a version of SLF4J older than 1.7.14
101 return StaticMDCBinder.SINGLETON.getMDCA();
102 }
103 }
104
105 static {
106 try {
107 mdcAdapter = bwCompatibleGetMDCAdapterFromBinder();
108 } catch (NoClassDefFoundError ncde) {
109 mdcAdapter = new NOPMDCAdapter();
110 String msg = ncde.getMessage();
111 if (msg != null && msg.contains("StaticMDCBinder")) {
112 Util.report("Failed to load class \"org.slf4j.impl.StaticMDCBinder\".");
113 Util.report("Defaulting to no-operation MDCAdapter implementation.");
114 Util.report("See " + NO_STATIC_MDC_BINDER_URL + " for further details.");
115 } else {
116 throw ncde;
117 }
118 } catch (Exception e) {
119 // we should never get here
120 Util.report("MDC binding unsuccessful.", e);
121 }
122 }
123
124 /**
125 * Put a diagnostic context value (the <code>val</code> parameter) as identified with the
126 * <code>key</code> parameter into the current thread's diagnostic context map. The
127 * <code>key</code> parameter cannot be null. The <code>val</code> parameter
128 * can be null only if the underlying implementation supports it.
129 *
130 * <p>
131 * This method delegates all work to the MDC of the underlying logging system.
132 *
133 * @param key non-null key
134 * @param val value to put in the map
135 *
136 * @throws IllegalArgumentException
137 * in case the "key" parameter is null
138 */
139 public static void put(String key, String val) throws IllegalArgumentException {
140 if (key == null) {
141 throw new IllegalArgumentException("key parameter cannot be null");
142 }
143 if (mdcAdapter == null) {
144 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
145 }
146 mdcAdapter.put(key, val);
147 }
148
149 /**
150 * Put a diagnostic context value (the <code>val</code> parameter) as identified with the
151 * <code>key</code> parameter into the current thread's diagnostic context map. The
152 * <code>key</code> parameter cannot be null. The <code>val</code> parameter
153 * can be null only if the underlying implementation supports it.
154 *
155 * <p>
156 * This method delegates all work to the MDC of the underlying logging system.
157 * <p>
158 * This method return a <code>Closeable</code> object who can remove <code>key</code> when
159 * <code>close</code> is called.
160 *
161 * <p>
162 * Useful with Java 7 for example :
163 * <code>
164 * try(MDC.MDCCloseable closeable = MDC.putCloseable(key, value)) {
165 * ....
166 * }
167 * </code>
168 *
169 * @param key non-null key
170 * @param val value to put in the map
171 * @return a <code>Closeable</code> who can remove <code>key</code> when <code>close</code>
172 * is called.
173 *
174 * @throws IllegalArgumentException
175 * in case the "key" parameter is null
176 */
177 public static MDCCloseable putCloseable(String key, String val) throws IllegalArgumentException {
178 put(key, val);
179 return new MDCCloseable(key);
180 }
181
182 /**
183 * Get the diagnostic context identified by the <code>key</code> parameter. The
184 * <code>key</code> parameter cannot be null.
185 *
186 * <p>
187 * This method delegates all work to the MDC of the underlying logging system.
188 *
189 * @param key
190 * @return the string value identified by the <code>key</code> parameter.
191 * @throws IllegalArgumentException
192 * in case the "key" parameter is null
193 */
194 public static String get(String key) throws IllegalArgumentException {
195 if (key == null) {
196 throw new IllegalArgumentException("key parameter cannot be null");
197 }
198
199 if (mdcAdapter == null) {
200 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
201 }
202 return mdcAdapter.get(key);
203 }
204
205 /**
206 * Remove the diagnostic context identified by the <code>key</code> parameter using
207 * the underlying system's MDC implementation. The <code>key</code> parameter
208 * cannot be null. This method does nothing if there is no previous value
209 * associated with <code>key</code>.
210 *
211 * @param key
212 * @throws IllegalArgumentException
213 * in case the "key" parameter is null
214 */
215 public static void remove(String key) throws IllegalArgumentException {
216 if (key == null) {
217 throw new IllegalArgumentException("key parameter cannot be null");
218 }
219
220 if (mdcAdapter == null) {
221 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
222 }
223 mdcAdapter.remove(key);
224 }
225
226 /**
227 * Clear all entries in the MDC of the underlying implementation.
228 */
229 public static void clear() {
230 if (mdcAdapter == null) {
231 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
232 }
233 mdcAdapter.clear();
234 }
235
236 /**
237 * Return a copy of the current thread's context map, with keys and values of
238 * type String. Returned value may be null.
239 *
240 * @return A copy of the current thread's context map. May be null.
241 * @since 1.5.1
242 */
243 public static Map<String, String> getCopyOfContextMap() {
244 if (mdcAdapter == null) {
245 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
246 }
247 return mdcAdapter.getCopyOfContextMap();
248 }
249
250 /**
251 * Set the current thread's context map by first clearing any existing map and
252 * then copying the map passed as parameter. The context map passed as
253 * parameter must only contain keys and values of type String.
254 *
255 * @param contextMap
256 * must contain only keys and values of type String
257 * @since 1.5.1
258 */
259 public static void setContextMap(Map<String, String> contextMap) {
260 if (mdcAdapter == null) {
261 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
262 }
263 mdcAdapter.setContextMap(contextMap);
264 }
265
266 /**
267 * Returns the MDCAdapter instance currently in use.
268 *
269 * @return the MDcAdapter instance currently in use.
270 * @since 1.4.2
271 */
272 public static MDCAdapter getMDCAdapter() {
273 return mdcAdapter;
274 }
275
276 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.Closeable;
27 import java.util.Map;
28
29 import org.slf4j.helpers.NOPMDCAdapter;
30 import org.slf4j.helpers.BasicMDCAdapter;
31 import org.slf4j.helpers.Util;
32 import org.slf4j.impl.StaticMDCBinder;
33 import org.slf4j.spi.MDCAdapter;
34
35 /**
36 * This class hides and serves as a substitute for the underlying logging
37 * system's MDC implementation.
38 *
39 * <p>
40 * If the underlying logging system offers MDC functionality, then SLF4J's MDC,
41 * i.e. this class, will delegate to the underlying system's MDC. Note that at
42 * this time, only two logging systems, namely log4j and logback, offer MDC
43 * functionality. For java.util.logging which does not support MDC,
44 * {@link BasicMDCAdapter} will be used. For other systems, i.e. slf4j-simple
45 * and slf4j-nop, {@link NOPMDCAdapter} will be used.
46 *
47 * <p>
48 * Thus, as a SLF4J user, you can take advantage of MDC in the presence of log4j,
49 * logback, or java.util.logging, but without forcing these systems as
50 * dependencies upon your users.
51 *
52 * <p>
53 * For more information on MDC please see the <a
54 * href="http://logback.qos.ch/manual/mdc.html">chapter on MDC</a> in the
55 * logback manual.
56 *
57 * <p>
58 * Please note that all methods in this class are static.
59 *
60 * @author Ceki G&uuml;lc&uuml;
61 * @since 1.4.1
62 */
63 public class MDC {
64
65 static final String NULL_MDCA_URL = "http://www.slf4j.org/codes.html#null_MDCA";
66 static final String NO_STATIC_MDC_BINDER_URL = "http://www.slf4j.org/codes.html#no_static_mdc_binder";
67 static MDCAdapter mdcAdapter;
68
69 /**
70 * An adapter to remove the key when done.
71 */
72 public static class MDCCloseable implements Closeable {
73 private final String key;
74
75 private MDCCloseable(String key) {
76 this.key = key;
77 }
78
79 public void close() {
80 MDC.remove(this.key);
81 }
82 }
83
84 private MDC() {
85 }
86
87 /**
88 * As of SLF4J version 1.7.14, StaticMDCBinder classes shipping in various bindings
89 * come with a getSingleton() method. Previously only a public field called SINGLETON
90 * was available.
91 *
92 * @return MDCAdapter
93 * @throws NoClassDefFoundError in case no binding is available
94 * @since 1.7.14
95 */
96 private static MDCAdapter bwCompatibleGetMDCAdapterFromBinder() throws NoClassDefFoundError {
97 try {
98 return StaticMDCBinder.getSingleton().getMDCA();
99 } catch (NoSuchMethodError nsme) {
100 // binding is probably a version of SLF4J older than 1.7.14
101 return StaticMDCBinder.SINGLETON.getMDCA();
102 }
103 }
104
105 static {
106 try {
107 mdcAdapter = bwCompatibleGetMDCAdapterFromBinder();
108 } catch (NoClassDefFoundError ncde) {
109 mdcAdapter = new NOPMDCAdapter();
110 String msg = ncde.getMessage();
111 if (msg != null && msg.contains("StaticMDCBinder")) {
112 Util.report("Failed to load class \"org.slf4j.impl.StaticMDCBinder\".");
113 Util.report("Defaulting to no-operation MDCAdapter implementation.");
114 Util.report("See " + NO_STATIC_MDC_BINDER_URL + " for further details.");
115 } else {
116 throw ncde;
117 }
118 } catch (Exception e) {
119 // we should never get here
120 Util.report("MDC binding unsuccessful.", e);
121 }
122 }
123
124 /**
125 * Put a diagnostic context value (the <code>val</code> parameter) as identified with the
126 * <code>key</code> parameter into the current thread's diagnostic context map. The
127 * <code>key</code> parameter cannot be null. The <code>val</code> parameter
128 * can be null only if the underlying implementation supports it.
129 *
130 * <p>
131 * This method delegates all work to the MDC of the underlying logging system.
132 *
133 * @param key non-null key
134 * @param val value to put in the map
135 *
136 * @throws IllegalArgumentException
137 * in case the "key" parameter is null
138 */
139 public static void put(String key, String val) throws IllegalArgumentException {
140 if (key == null) {
141 throw new IllegalArgumentException("key parameter cannot be null");
142 }
143 if (mdcAdapter == null) {
144 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
145 }
146 mdcAdapter.put(key, val);
147 }
148
149 /**
150 * Put a diagnostic context value (the <code>val</code> parameter) as identified with the
151 * <code>key</code> parameter into the current thread's diagnostic context map. The
152 * <code>key</code> parameter cannot be null. The <code>val</code> parameter
153 * can be null only if the underlying implementation supports it.
154 *
155 * <p>
156 * This method delegates all work to the MDC of the underlying logging system.
157 * <p>
158 * This method return a <code>Closeable</code> object who can remove <code>key</code> when
159 * <code>close</code> is called.
160 *
161 * <p>
162 * Useful with Java 7 for example :
163 * <code>
164 * try(MDC.MDCCloseable closeable = MDC.putCloseable(key, value)) {
165 * ....
166 * }
167 * </code>
168 *
169 * @param key non-null key
170 * @param val value to put in the map
171 * @return a <code>Closeable</code> who can remove <code>key</code> when <code>close</code>
172 * is called.
173 *
174 * @throws IllegalArgumentException
175 * in case the "key" parameter is null
176 */
177 public static MDCCloseable putCloseable(String key, String val) throws IllegalArgumentException {
178 put(key, val);
179 return new MDCCloseable(key);
180 }
181
182 /**
183 * Get the diagnostic context identified by the <code>key</code> parameter. The
184 * <code>key</code> parameter cannot be null.
185 *
186 * <p>
187 * This method delegates all work to the MDC of the underlying logging system.
188 *
189 * @param key
190 * @return the string value identified by the <code>key</code> parameter.
191 * @throws IllegalArgumentException
192 * in case the "key" parameter is null
193 */
194 public static String get(String key) throws IllegalArgumentException {
195 if (key == null) {
196 throw new IllegalArgumentException("key parameter cannot be null");
197 }
198
199 if (mdcAdapter == null) {
200 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
201 }
202 return mdcAdapter.get(key);
203 }
204
205 /**
206 * Remove the diagnostic context identified by the <code>key</code> parameter using
207 * the underlying system's MDC implementation. The <code>key</code> parameter
208 * cannot be null. This method does nothing if there is no previous value
209 * associated with <code>key</code>.
210 *
211 * @param key
212 * @throws IllegalArgumentException
213 * in case the "key" parameter is null
214 */
215 public static void remove(String key) throws IllegalArgumentException {
216 if (key == null) {
217 throw new IllegalArgumentException("key parameter cannot be null");
218 }
219
220 if (mdcAdapter == null) {
221 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
222 }
223 mdcAdapter.remove(key);
224 }
225
226 /**
227 * Clear all entries in the MDC of the underlying implementation.
228 */
229 public static void clear() {
230 if (mdcAdapter == null) {
231 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
232 }
233 mdcAdapter.clear();
234 }
235
236 /**
237 * Return a copy of the current thread's context map, with keys and values of
238 * type String. Returned value may be null.
239 *
240 * @return A copy of the current thread's context map. May be null.
241 * @since 1.5.1
242 */
243 public static Map<String, String> getCopyOfContextMap() {
244 if (mdcAdapter == null) {
245 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
246 }
247 return mdcAdapter.getCopyOfContextMap();
248 }
249
250 /**
251 * Set the current thread's context map by first clearing any existing map and
252 * then copying the map passed as parameter. The context map passed as
253 * parameter must only contain keys and values of type String.
254 *
255 * @param contextMap
256 * must contain only keys and values of type String
257 * @since 1.5.1
258 */
259 public static void setContextMap(Map<String, String> contextMap) {
260 if (mdcAdapter == null) {
261 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
262 }
263 mdcAdapter.setContextMap(contextMap);
264 }
265
266 /**
267 * Returns the MDCAdapter instance currently in use.
268 *
269 * @return the MDcAdapter instance currently in use.
270 * @since 1.4.2
271 */
272 public static MDCAdapter getMDCAdapter() {
273 return mdcAdapter;
274 }
275
276 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.Serializable;
27 import java.util.Iterator;
28
29 /**
30 * Markers are named objects used to enrich log statements. Conforming logging
31 * system Implementations of SLF4J determine how information conveyed by markers
32 * are used, if at all. In particular, many conforming logging systems ignore
33 * marker data.
34 *
35 * <p>
36 * Markers can contain references to other markers, which in turn may contain
37 * references of their own.
38 *
39 * @author Ceki G&uuml;lc&uuml;
40 */
41 public interface Marker extends Serializable {
42
43 /**
44 * This constant represents any marker, including a null marker.
45 */
46 public final String ANY_MARKER = "*";
47
48 /**
49 * This constant represents any non-null marker.
50 */
51 public final String ANY_NON_NULL_MARKER = "+";
52
53 /**
54 * Get the name of this Marker.
55 *
56 * @return name of marker
57 */
58 public String getName();
59
60 /**
61 * Add a reference to another Marker.
62 *
63 * @param reference
64 * a reference to another marker
65 * @throws IllegalArgumentException
66 * if 'reference' is null
67 */
68 public void add(Marker reference);
69
70 /**
71 * Remove a marker reference.
72 *
73 * @param reference
74 * the marker reference to remove
75 * @return true if reference could be found and removed, false otherwise.
76 */
77 public boolean remove(Marker reference);
78
79 /**
80 * @deprecated Replaced by {@link #hasReferences()}.
81 */
82 public boolean hasChildren();
83
84 /**
85 * Does this marker have any references?
86 *
87 * @return true if this marker has one or more references, false otherwise.
88 */
89 public boolean hasReferences();
90
91 /**
92 * Returns an Iterator which can be used to iterate over the references of this
93 * marker. An empty iterator is returned when this marker has no references.
94 *
95 * @return Iterator over the references of this marker
96 */
97 public Iterator<Marker> iterator();
98
99 /**
100 * Does this marker contain a reference to the 'other' marker? Marker A is defined
101 * to contain marker B, if A == B or if B is referenced by A, or if B is referenced
102 * by any one of A's references (recursively).
103 *
104 * @param other
105 * The marker to test for inclusion.
106 * @throws IllegalArgumentException
107 * if 'other' is null
108 * @return Whether this marker contains the other marker.
109 */
110 public boolean contains(Marker other);
111
112 /**
113 * Does this marker contain the marker named 'name'?
114 *
115 * If 'name' is null the returned value is always false.
116 *
117 * @param name The marker name to test for inclusion.
118 * @return Whether this marker contains the other marker.
119 */
120 public boolean contains(String name);
121
122 /**
123 * Markers are considered equal if they have the same name.
124 *
125 * @param o
126 * @return true, if this.name equals o.name
127 *
128 * @since 1.5.1
129 */
130 public boolean equals(Object o);
131
132 /**
133 * Compute the hash code based on the name of this marker.
134 * Note that markers are considered equal if they have the same name.
135 *
136 * @return the computed hashCode
137 * @since 1.5.1
138 */
139 public int hashCode();
140
141 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.Serializable;
27 import java.util.Iterator;
28
29 /**
30 * Markers are named objects used to enrich log statements. Conforming logging
31 * system Implementations of SLF4J determine how information conveyed by markers
32 * are used, if at all. In particular, many conforming logging systems ignore
33 * marker data.
34 *
35 * <p>
36 * Markers can contain references to other markers, which in turn may contain
37 * references of their own.
38 *
39 * @author Ceki G&uuml;lc&uuml;
40 */
41 public interface Marker extends Serializable {
42
43 /**
44 * This constant represents any marker, including a null marker.
45 */
46 public final String ANY_MARKER = "*";
47
48 /**
49 * This constant represents any non-null marker.
50 */
51 public final String ANY_NON_NULL_MARKER = "+";
52
53 /**
54 * Get the name of this Marker.
55 *
56 * @return name of marker
57 */
58 public String getName();
59
60 /**
61 * Add a reference to another Marker.
62 *
63 * @param reference
64 * a reference to another marker
65 * @throws IllegalArgumentException
66 * if 'reference' is null
67 */
68 public void add(Marker reference);
69
70 /**
71 * Remove a marker reference.
72 *
73 * @param reference
74 * the marker reference to remove
75 * @return true if reference could be found and removed, false otherwise.
76 */
77 public boolean remove(Marker reference);
78
79 /**
80 * @deprecated Replaced by {@link #hasReferences()}.
81 */
82 public boolean hasChildren();
83
84 /**
85 * Does this marker have any references?
86 *
87 * @return true if this marker has one or more references, false otherwise.
88 */
89 public boolean hasReferences();
90
91 /**
92 * Returns an Iterator which can be used to iterate over the references of this
93 * marker. An empty iterator is returned when this marker has no references.
94 *
95 * @return Iterator over the references of this marker
96 */
97 public Iterator<Marker> iterator();
98
99 /**
100 * Does this marker contain a reference to the 'other' marker? Marker A is defined
101 * to contain marker B, if A == B or if B is referenced by A, or if B is referenced
102 * by any one of A's references (recursively).
103 *
104 * @param other
105 * The marker to test for inclusion.
106 * @throws IllegalArgumentException
107 * if 'other' is null
108 * @return Whether this marker contains the other marker.
109 */
110 public boolean contains(Marker other);
111
112 /**
113 * Does this marker contain the marker named 'name'?
114 *
115 * If 'name' is null the returned value is always false.
116 *
117 * @param name The marker name to test for inclusion.
118 * @return Whether this marker contains the other marker.
119 */
120 public boolean contains(String name);
121
122 /**
123 * Markers are considered equal if they have the same name.
124 *
125 * @param o
126 * @return true, if this.name equals o.name
127 *
128 * @since 1.5.1
129 */
130 public boolean equals(Object o);
131
132 /**
133 * Compute the hash code based on the name of this marker.
134 * Note that markers are considered equal if they have the same name.
135 *
136 * @return the computed hashCode
137 * @since 1.5.1
138 */
139 public int hashCode();
140
141 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import org.slf4j.helpers.BasicMarkerFactory;
27 import org.slf4j.helpers.Util;
28 import org.slf4j.impl.StaticMarkerBinder;
29
30 /**
31 * MarkerFactory is a utility class producing {@link Marker} instances as
32 * appropriate for the logging system currently in use.
33 *
34 * <p>
35 * This class is essentially implemented as a wrapper around an
36 * {@link IMarkerFactory} instance bound at compile time.
37 *
38 * <p>
39 * Please note that all methods in this class are static.
40 *
41 * @author Ceki G&uuml;lc&uuml;
42 */
43 public class MarkerFactory {
44 static IMarkerFactory MARKER_FACTORY;
45
46 private MarkerFactory() {
47 }
48
49 /**
50 * As of SLF4J version 1.7.14, StaticMarkerBinder classes shipping in various bindings
51 * come with a getSingleton() method. Previously only a public field called SINGLETON
52 * was available.
53 *
54 * @return IMarkerFactory
55 * @throws NoClassDefFoundError in case no binding is available
56 * @since 1.7.14
57 */
58 private static IMarkerFactory bwCompatibleGetMarkerFactoryFromBinder() throws NoClassDefFoundError {
59 try {
60 return StaticMarkerBinder.getSingleton().getMarkerFactory();
61 } catch (NoSuchMethodError nsme) {
62 // binding is probably a version of SLF4J older than 1.7.14
63 return StaticMarkerBinder.SINGLETON.getMarkerFactory();
64 }
65 }
66
67 // this is where the binding happens
68 static {
69 try {
70 MARKER_FACTORY = bwCompatibleGetMarkerFactoryFromBinder();
71 } catch (NoClassDefFoundError e) {
72 MARKER_FACTORY = new BasicMarkerFactory();
73 } catch (Exception e) {
74 // we should never get here
75 Util.report("Unexpected failure while binding MarkerFactory", e);
76 }
77 }
78
79 /**
80 * Return a Marker instance as specified by the name parameter using the
81 * previously bound {@link IMarkerFactory}instance.
82 *
83 * @param name
84 * The name of the {@link Marker} object to return.
85 * @return marker
86 */
87 public static Marker getMarker(String name) {
88 return MARKER_FACTORY.getMarker(name);
89 }
90
91 /**
92 * Create a marker which is detached (even at birth) from the MarkerFactory.
93 *
94 * @param name the name of the marker
95 * @return a dangling marker
96 * @since 1.5.1
97 */
98 public static Marker getDetachedMarker(String name) {
99 return MARKER_FACTORY.getDetachedMarker(name);
100 }
101
102 /**
103 * Return the {@link IMarkerFactory}instance in use.
104 *
105 * <p>The IMarkerFactory instance is usually bound with this class at
106 * compile time.
107 *
108 * @return the IMarkerFactory instance in use
109 */
110 public static IMarkerFactory getIMarkerFactory() {
111 return MARKER_FACTORY;
112 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import org.slf4j.helpers.BasicMarkerFactory;
27 import org.slf4j.helpers.Util;
28 import org.slf4j.impl.StaticMarkerBinder;
29
30 /**
31 * MarkerFactory is a utility class producing {@link Marker} instances as
32 * appropriate for the logging system currently in use.
33 *
34 * <p>
35 * This class is essentially implemented as a wrapper around an
36 * {@link IMarkerFactory} instance bound at compile time.
37 *
38 * <p>
39 * Please note that all methods in this class are static.
40 *
41 * @author Ceki G&uuml;lc&uuml;
42 */
43 public class MarkerFactory {
44 static IMarkerFactory MARKER_FACTORY;
45
46 private MarkerFactory() {
47 }
48
49 /**
50 * As of SLF4J version 1.7.14, StaticMarkerBinder classes shipping in various bindings
51 * come with a getSingleton() method. Previously only a public field called SINGLETON
52 * was available.
53 *
54 * @return IMarkerFactory
55 * @throws NoClassDefFoundError in case no binding is available
56 * @since 1.7.14
57 */
58 private static IMarkerFactory bwCompatibleGetMarkerFactoryFromBinder() throws NoClassDefFoundError {
59 try {
60 return StaticMarkerBinder.getSingleton().getMarkerFactory();
61 } catch (NoSuchMethodError nsme) {
62 // binding is probably a version of SLF4J older than 1.7.14
63 return StaticMarkerBinder.SINGLETON.getMarkerFactory();
64 }
65 }
66
67 // this is where the binding happens
68 static {
69 try {
70 MARKER_FACTORY = bwCompatibleGetMarkerFactoryFromBinder();
71 } catch (NoClassDefFoundError e) {
72 MARKER_FACTORY = new BasicMarkerFactory();
73 } catch (Exception e) {
74 // we should never get here
75 Util.report("Unexpected failure while binding MarkerFactory", e);
76 }
77 }
78
79 /**
80 * Return a Marker instance as specified by the name parameter using the
81 * previously bound {@link IMarkerFactory}instance.
82 *
83 * @param name
84 * The name of the {@link Marker} object to return.
85 * @return marker
86 */
87 public static Marker getMarker(String name) {
88 return MARKER_FACTORY.getMarker(name);
89 }
90
91 /**
92 * Create a marker which is detached (even at birth) from the MarkerFactory.
93 *
94 * @param name the name of the marker
95 * @return a dangling marker
96 * @since 1.5.1
97 */
98 public static Marker getDetachedMarker(String name) {
99 return MARKER_FACTORY.getDetachedMarker(name);
100 }
101
102 /**
103 * Return the {@link IMarkerFactory}instance in use.
104 *
105 * <p>The IMarkerFactory instance is usually bound with this class at
106 * compile time.
107 *
108 * @return the IMarkerFactory instance in use
109 */
110 public static IMarkerFactory getIMarkerFactory() {
111 return MARKER_FACTORY;
112 }
113113 }
0 package org.slf4j.event;
1
2 import org.slf4j.spi.LocationAwareLogger;
3
4 public class EventConstants {
5 public static final int ERROR_INT = LocationAwareLogger.ERROR_INT;
6 public static final int WARN_INT = LocationAwareLogger.WARN_INT;
7 public static final int INFO_INT = LocationAwareLogger.INFO_INT;
8 public static final int DEBUG_INT = LocationAwareLogger.DEBUG_INT;
9 public static final int TRACE_INT = LocationAwareLogger.TRACE_INT;
10 public static final String NA_SUBST = "NA/SubstituteLogger";
11
12 }
0 package org.slf4j.event;
1
2 import org.slf4j.spi.LocationAwareLogger;
3
4 public class EventConstants {
5 public static final int ERROR_INT = LocationAwareLogger.ERROR_INT;
6 public static final int WARN_INT = LocationAwareLogger.WARN_INT;
7 public static final int INFO_INT = LocationAwareLogger.INFO_INT;
8 public static final int DEBUG_INT = LocationAwareLogger.DEBUG_INT;
9 public static final int TRACE_INT = LocationAwareLogger.TRACE_INT;
10 public static final String NA_SUBST = "NA/SubstituteLogger";
11
12 }
0 package org.slf4j.event;
1
2 import java.util.Queue;
3
4 import org.slf4j.Logger;
5 import org.slf4j.Marker;
6 import org.slf4j.helpers.SubstituteLogger;
7
8 public class EventRecodingLogger implements Logger {
9
10 String name;
11 SubstituteLogger logger;
12 Queue<SubstituteLoggingEvent> eventQueue;
13
14 public EventRecodingLogger(SubstituteLogger logger, Queue<SubstituteLoggingEvent> eventQueue) {
15 this.logger = logger;
16 this.name = logger.getName();
17 this.eventQueue = eventQueue;
18 }
19
20 public String getName() {
21 return name;
22 }
23
24 private void recordEvent(Level level, String msg, Object[] args, Throwable throwable) {
25 recordEvent(level, null, msg, args, throwable);
26 }
27
28 private void recordEvent(Level level, Marker marker, String msg, Object[] args, Throwable throwable) {
29 // System.out.println("recording logger:"+name+", msg:"+msg);
30 SubstituteLoggingEvent loggingEvent = new SubstituteLoggingEvent();
31 loggingEvent.setTimeStamp(System.currentTimeMillis());
32 loggingEvent.setLevel(level);
33 loggingEvent.setLogger(logger);
34 loggingEvent.setLoggerName(name);
35 loggingEvent.setMarker(marker);
36 loggingEvent.setMessage(msg);
37 loggingEvent.setArgumentArray(args);
38 loggingEvent.setThrowable(throwable);
39 loggingEvent.setThreadName(Thread.currentThread().getName());
40 eventQueue.add(loggingEvent);
41 }
42
43 public boolean isTraceEnabled() {
44 return true;
45 }
46
47 public void trace(String msg) {
48 recordEvent(Level.TRACE, msg, null, null);
49 }
50
51 public void trace(String format, Object arg) {
52 recordEvent(Level.TRACE, format, new Object[] { arg }, null);
53 }
54
55 public void trace(String format, Object arg1, Object arg2) {
56 recordEvent(Level.TRACE, format, new Object[] { arg1, arg2 }, null);
57 }
58
59 public void trace(String format, Object... arguments) {
60 recordEvent(Level.TRACE, format, arguments, null);
61 }
62
63 public void trace(String msg, Throwable t) {
64 recordEvent(Level.TRACE, msg, null, t);
65 }
66
67 public boolean isTraceEnabled(Marker marker) {
68 return true;
69 }
70
71 public void trace(Marker marker, String msg) {
72 recordEvent(Level.TRACE, marker, msg, null, null);
73
74 }
75
76 public void trace(Marker marker, String format, Object arg) {
77 recordEvent(Level.TRACE, marker, format, new Object[] { arg }, null);
78 }
79
80 public void trace(Marker marker, String format, Object arg1, Object arg2) {
81 recordEvent(Level.TRACE, marker, format, new Object[] { arg1, arg2 }, null);
82 }
83
84 public void trace(Marker marker, String format, Object... argArray) {
85 recordEvent(Level.TRACE, marker, format, argArray, null);
86
87 }
88
89 public void trace(Marker marker, String msg, Throwable t) {
90 recordEvent(Level.TRACE, marker, msg, null, t);
91 }
92
93 public boolean isDebugEnabled() {
94 return true;
95 }
96
97 public void debug(String msg) {
98 recordEvent(Level.TRACE, msg, null, null);
99 }
100
101 public void debug(String format, Object arg) {
102 recordEvent(Level.DEBUG, format, new Object[] { arg }, null);
103
104 }
105
106 public void debug(String format, Object arg1, Object arg2) {
107 recordEvent(Level.DEBUG, format, new Object[] { arg1, arg2 }, null);
108
109 }
110
111 public void debug(String format, Object... arguments) {
112 recordEvent(Level.DEBUG, format, arguments, null);
113 }
114
115 public void debug(String msg, Throwable t) {
116 recordEvent(Level.DEBUG, msg, null, t);
117 }
118
119 public boolean isDebugEnabled(Marker marker) {
120 return true;
121 }
122
123 public void debug(Marker marker, String msg) {
124 recordEvent(Level.DEBUG, marker, msg, null, null);
125 }
126
127 public void debug(Marker marker, String format, Object arg) {
128 recordEvent(Level.DEBUG, marker, format, new Object[] { arg }, null);
129 }
130
131 public void debug(Marker marker, String format, Object arg1, Object arg2) {
132 recordEvent(Level.DEBUG, marker, format, new Object[] { arg1, arg2 }, null);
133 }
134
135 public void debug(Marker marker, String format, Object... arguments) {
136 recordEvent(Level.DEBUG, marker, format, arguments, null);
137 }
138
139 public void debug(Marker marker, String msg, Throwable t) {
140 recordEvent(Level.DEBUG, marker, msg, null, t);
141 }
142
143 public boolean isInfoEnabled() {
144 return true;
145 }
146
147 public void info(String msg) {
148 recordEvent(Level.INFO, msg, null, null);
149 }
150
151 public void info(String format, Object arg) {
152 recordEvent(Level.INFO, format, new Object[] { arg }, null);
153 }
154
155 public void info(String format, Object arg1, Object arg2) {
156 recordEvent(Level.INFO, format, new Object[] { arg1, arg2 }, null);
157 }
158
159 public void info(String format, Object... arguments) {
160 recordEvent(Level.INFO, format, arguments, null);
161 }
162
163 public void info(String msg, Throwable t) {
164 recordEvent(Level.INFO, msg, null, t);
165 }
166
167 public boolean isInfoEnabled(Marker marker) {
168 return true;
169 }
170
171 public void info(Marker marker, String msg) {
172 recordEvent(Level.INFO, marker, msg, null, null);
173 }
174
175 public void info(Marker marker, String format, Object arg) {
176 recordEvent(Level.INFO, marker, format, new Object[] { arg }, null);
177 }
178
179 public void info(Marker marker, String format, Object arg1, Object arg2) {
180 recordEvent(Level.INFO, marker, format, new Object[] { arg1, arg2 }, null);
181 }
182
183 public void info(Marker marker, String format, Object... arguments) {
184 recordEvent(Level.INFO, marker, format, arguments, null);
185 }
186
187 public void info(Marker marker, String msg, Throwable t) {
188 recordEvent(Level.INFO, marker, msg, null, t);
189
190 }
191
192 public boolean isWarnEnabled() {
193 return true;
194 }
195
196 public void warn(String msg) {
197 recordEvent(Level.WARN, msg, null, null);
198 }
199
200 public void warn(String format, Object arg) {
201 recordEvent(Level.WARN, format, new Object[] { arg }, null);
202
203 }
204
205 public void warn(String format, Object arg1, Object arg2) {
206 recordEvent(Level.WARN, format, new Object[] { arg1, arg2 }, null);
207 }
208
209 public void warn(String format, Object... arguments) {
210 recordEvent(Level.WARN, format, arguments, null);
211 }
212
213 public void warn(String msg, Throwable t) {
214 recordEvent(Level.WARN, msg, null, t);
215 }
216
217 public boolean isWarnEnabled(Marker marker) {
218 return true;
219 }
220
221 public void warn(Marker marker, String msg) {
222 recordEvent(Level.WARN, msg, null, null);
223 }
224
225 public void warn(Marker marker, String format, Object arg) {
226 recordEvent(Level.WARN, format, new Object[] { arg }, null);
227 }
228
229 public void warn(Marker marker, String format, Object arg1, Object arg2) {
230 recordEvent(Level.WARN, marker, format, new Object[] { arg1, arg2 }, null);
231
232 }
233
234 public void warn(Marker marker, String format, Object... arguments) {
235 recordEvent(Level.WARN, marker, format, arguments, null);
236 }
237
238 public void warn(Marker marker, String msg, Throwable t) {
239 recordEvent(Level.WARN, marker, msg, null, t);
240 }
241
242 public boolean isErrorEnabled() {
243 return true;
244 }
245
246 public void error(String msg) {
247 recordEvent(Level.ERROR, msg, null, null);
248 }
249
250 public void error(String format, Object arg) {
251 recordEvent(Level.ERROR, format, new Object[] { arg }, null);
252
253 }
254
255 public void error(String format, Object arg1, Object arg2) {
256 recordEvent(Level.ERROR, format, new Object[] { arg1, arg2 }, null);
257
258 }
259
260 public void error(String format, Object... arguments) {
261 recordEvent(Level.ERROR, format, arguments, null);
262
263 }
264
265 public void error(String msg, Throwable t) {
266 recordEvent(Level.ERROR, msg, null, t);
267 }
268
269 public boolean isErrorEnabled(Marker marker) {
270 return true;
271 }
272
273 public void error(Marker marker, String msg) {
274 recordEvent(Level.ERROR, marker, msg, null, null);
275
276 }
277
278 public void error(Marker marker, String format, Object arg) {
279 recordEvent(Level.ERROR, marker, format, new Object[] { arg }, null);
280
281 }
282
283 public void error(Marker marker, String format, Object arg1, Object arg2) {
284 recordEvent(Level.ERROR, marker, format, new Object[] { arg1, arg2 }, null);
285 }
286
287 public void error(Marker marker, String format, Object... arguments) {
288 recordEvent(Level.ERROR, marker, format, arguments, null);
289 }
290
291 public void error(Marker marker, String msg, Throwable t) {
292 recordEvent(Level.ERROR, marker, msg, null, t);
293 }
294
295 }
0 package org.slf4j.event;
1
2 import java.util.Queue;
3
4 import org.slf4j.Logger;
5 import org.slf4j.Marker;
6 import org.slf4j.helpers.SubstituteLogger;
7
8 public class EventRecodingLogger implements Logger {
9
10 String name;
11 SubstituteLogger logger;
12 Queue<SubstituteLoggingEvent> eventQueue;
13
14 public EventRecodingLogger(SubstituteLogger logger, Queue<SubstituteLoggingEvent> eventQueue) {
15 this.logger = logger;
16 this.name = logger.getName();
17 this.eventQueue = eventQueue;
18 }
19
20 public String getName() {
21 return name;
22 }
23
24 private void recordEvent(Level level, String msg, Object[] args, Throwable throwable) {
25 recordEvent(level, null, msg, args, throwable);
26 }
27
28 private void recordEvent(Level level, Marker marker, String msg, Object[] args, Throwable throwable) {
29 // System.out.println("recording logger:"+name+", msg:"+msg);
30 SubstituteLoggingEvent loggingEvent = new SubstituteLoggingEvent();
31 loggingEvent.setTimeStamp(System.currentTimeMillis());
32 loggingEvent.setLevel(level);
33 loggingEvent.setLogger(logger);
34 loggingEvent.setLoggerName(name);
35 loggingEvent.setMarker(marker);
36 loggingEvent.setMessage(msg);
37 loggingEvent.setArgumentArray(args);
38 loggingEvent.setThrowable(throwable);
39 loggingEvent.setThreadName(Thread.currentThread().getName());
40 eventQueue.add(loggingEvent);
41 }
42
43 public boolean isTraceEnabled() {
44 return true;
45 }
46
47 public void trace(String msg) {
48 recordEvent(Level.TRACE, msg, null, null);
49 }
50
51 public void trace(String format, Object arg) {
52 recordEvent(Level.TRACE, format, new Object[] { arg }, null);
53 }
54
55 public void trace(String format, Object arg1, Object arg2) {
56 recordEvent(Level.TRACE, format, new Object[] { arg1, arg2 }, null);
57 }
58
59 public void trace(String format, Object... arguments) {
60 recordEvent(Level.TRACE, format, arguments, null);
61 }
62
63 public void trace(String msg, Throwable t) {
64 recordEvent(Level.TRACE, msg, null, t);
65 }
66
67 public boolean isTraceEnabled(Marker marker) {
68 return true;
69 }
70
71 public void trace(Marker marker, String msg) {
72 recordEvent(Level.TRACE, marker, msg, null, null);
73
74 }
75
76 public void trace(Marker marker, String format, Object arg) {
77 recordEvent(Level.TRACE, marker, format, new Object[] { arg }, null);
78 }
79
80 public void trace(Marker marker, String format, Object arg1, Object arg2) {
81 recordEvent(Level.TRACE, marker, format, new Object[] { arg1, arg2 }, null);
82 }
83
84 public void trace(Marker marker, String format, Object... argArray) {
85 recordEvent(Level.TRACE, marker, format, argArray, null);
86
87 }
88
89 public void trace(Marker marker, String msg, Throwable t) {
90 recordEvent(Level.TRACE, marker, msg, null, t);
91 }
92
93 public boolean isDebugEnabled() {
94 return true;
95 }
96
97 public void debug(String msg) {
98 recordEvent(Level.TRACE, msg, null, null);
99 }
100
101 public void debug(String format, Object arg) {
102 recordEvent(Level.DEBUG, format, new Object[] { arg }, null);
103
104 }
105
106 public void debug(String format, Object arg1, Object arg2) {
107 recordEvent(Level.DEBUG, format, new Object[] { arg1, arg2 }, null);
108
109 }
110
111 public void debug(String format, Object... arguments) {
112 recordEvent(Level.DEBUG, format, arguments, null);
113 }
114
115 public void debug(String msg, Throwable t) {
116 recordEvent(Level.DEBUG, msg, null, t);
117 }
118
119 public boolean isDebugEnabled(Marker marker) {
120 return true;
121 }
122
123 public void debug(Marker marker, String msg) {
124 recordEvent(Level.DEBUG, marker, msg, null, null);
125 }
126
127 public void debug(Marker marker, String format, Object arg) {
128 recordEvent(Level.DEBUG, marker, format, new Object[] { arg }, null);
129 }
130
131 public void debug(Marker marker, String format, Object arg1, Object arg2) {
132 recordEvent(Level.DEBUG, marker, format, new Object[] { arg1, arg2 }, null);
133 }
134
135 public void debug(Marker marker, String format, Object... arguments) {
136 recordEvent(Level.DEBUG, marker, format, arguments, null);
137 }
138
139 public void debug(Marker marker, String msg, Throwable t) {
140 recordEvent(Level.DEBUG, marker, msg, null, t);
141 }
142
143 public boolean isInfoEnabled() {
144 return true;
145 }
146
147 public void info(String msg) {
148 recordEvent(Level.INFO, msg, null, null);
149 }
150
151 public void info(String format, Object arg) {
152 recordEvent(Level.INFO, format, new Object[] { arg }, null);
153 }
154
155 public void info(String format, Object arg1, Object arg2) {
156 recordEvent(Level.INFO, format, new Object[] { arg1, arg2 }, null);
157 }
158
159 public void info(String format, Object... arguments) {
160 recordEvent(Level.INFO, format, arguments, null);
161 }
162
163 public void info(String msg, Throwable t) {
164 recordEvent(Level.INFO, msg, null, t);
165 }
166
167 public boolean isInfoEnabled(Marker marker) {
168 return true;
169 }
170
171 public void info(Marker marker, String msg) {
172 recordEvent(Level.INFO, marker, msg, null, null);
173 }
174
175 public void info(Marker marker, String format, Object arg) {
176 recordEvent(Level.INFO, marker, format, new Object[] { arg }, null);
177 }
178
179 public void info(Marker marker, String format, Object arg1, Object arg2) {
180 recordEvent(Level.INFO, marker, format, new Object[] { arg1, arg2 }, null);
181 }
182
183 public void info(Marker marker, String format, Object... arguments) {
184 recordEvent(Level.INFO, marker, format, arguments, null);
185 }
186
187 public void info(Marker marker, String msg, Throwable t) {
188 recordEvent(Level.INFO, marker, msg, null, t);
189
190 }
191
192 public boolean isWarnEnabled() {
193 return true;
194 }
195
196 public void warn(String msg) {
197 recordEvent(Level.WARN, msg, null, null);
198 }
199
200 public void warn(String format, Object arg) {
201 recordEvent(Level.WARN, format, new Object[] { arg }, null);
202
203 }
204
205 public void warn(String format, Object arg1, Object arg2) {
206 recordEvent(Level.WARN, format, new Object[] { arg1, arg2 }, null);
207 }
208
209 public void warn(String format, Object... arguments) {
210 recordEvent(Level.WARN, format, arguments, null);
211 }
212
213 public void warn(String msg, Throwable t) {
214 recordEvent(Level.WARN, msg, null, t);
215 }
216
217 public boolean isWarnEnabled(Marker marker) {
218 return true;
219 }
220
221 public void warn(Marker marker, String msg) {
222 recordEvent(Level.WARN, msg, null, null);
223 }
224
225 public void warn(Marker marker, String format, Object arg) {
226 recordEvent(Level.WARN, format, new Object[] { arg }, null);
227 }
228
229 public void warn(Marker marker, String format, Object arg1, Object arg2) {
230 recordEvent(Level.WARN, marker, format, new Object[] { arg1, arg2 }, null);
231
232 }
233
234 public void warn(Marker marker, String format, Object... arguments) {
235 recordEvent(Level.WARN, marker, format, arguments, null);
236 }
237
238 public void warn(Marker marker, String msg, Throwable t) {
239 recordEvent(Level.WARN, marker, msg, null, t);
240 }
241
242 public boolean isErrorEnabled() {
243 return true;
244 }
245
246 public void error(String msg) {
247 recordEvent(Level.ERROR, msg, null, null);
248 }
249
250 public void error(String format, Object arg) {
251 recordEvent(Level.ERROR, format, new Object[] { arg }, null);
252
253 }
254
255 public void error(String format, Object arg1, Object arg2) {
256 recordEvent(Level.ERROR, format, new Object[] { arg1, arg2 }, null);
257
258 }
259
260 public void error(String format, Object... arguments) {
261 recordEvent(Level.ERROR, format, arguments, null);
262
263 }
264
265 public void error(String msg, Throwable t) {
266 recordEvent(Level.ERROR, msg, null, t);
267 }
268
269 public boolean isErrorEnabled(Marker marker) {
270 return true;
271 }
272
273 public void error(Marker marker, String msg) {
274 recordEvent(Level.ERROR, marker, msg, null, null);
275
276 }
277
278 public void error(Marker marker, String format, Object arg) {
279 recordEvent(Level.ERROR, marker, format, new Object[] { arg }, null);
280
281 }
282
283 public void error(Marker marker, String format, Object arg1, Object arg2) {
284 recordEvent(Level.ERROR, marker, format, new Object[] { arg1, arg2 }, null);
285 }
286
287 public void error(Marker marker, String format, Object... arguments) {
288 recordEvent(Level.ERROR, marker, format, arguments, null);
289 }
290
291 public void error(Marker marker, String msg, Throwable t) {
292 recordEvent(Level.ERROR, marker, msg, null, t);
293 }
294
295 }
0 package org.slf4j.event;
1
2 import static org.slf4j.event.EventConstants.DEBUG_INT;
3 import static org.slf4j.event.EventConstants.ERROR_INT;
4 import static org.slf4j.event.EventConstants.INFO_INT;
5 import static org.slf4j.event.EventConstants.TRACE_INT;
6 import static org.slf4j.event.EventConstants.WARN_INT;
7
8 /**
9 *
10 * @author ceki
11 * @since 1.7.15
12 */
13 public enum Level {
14
15 ERROR(ERROR_INT, "ERROR"), WARN(WARN_INT, "WARN"), INFO(INFO_INT, "INFO"), DEBUG(DEBUG_INT, "DEBUG"), TRACE(TRACE_INT, "TRACE");
16
17 private int levelInt;
18 private String levelStr;
19
20 Level(int i, String s) {
21 levelInt = i;
22 levelStr = s;
23 }
24
25 public int toInt() {
26 return levelInt;
27 }
28
29 /**
30 * Returns the string representation of this Level.
31 */
32 public String toString() {
33 return levelStr;
34 }
35
36 }
0 package org.slf4j.event;
1
2 import static org.slf4j.event.EventConstants.DEBUG_INT;
3 import static org.slf4j.event.EventConstants.ERROR_INT;
4 import static org.slf4j.event.EventConstants.INFO_INT;
5 import static org.slf4j.event.EventConstants.TRACE_INT;
6 import static org.slf4j.event.EventConstants.WARN_INT;
7
8 /**
9 *
10 * @author ceki
11 * @since 1.7.15
12 */
13 public enum Level {
14
15 ERROR(ERROR_INT, "ERROR"), WARN(WARN_INT, "WARN"), INFO(INFO_INT, "INFO"), DEBUG(DEBUG_INT, "DEBUG"), TRACE(TRACE_INT, "TRACE");
16
17 private int levelInt;
18 private String levelStr;
19
20 Level(int i, String s) {
21 levelInt = i;
22 levelStr = s;
23 }
24
25 public int toInt() {
26 return levelInt;
27 }
28
29 /**
30 * Returns the string representation of this Level.
31 */
32 public String toString() {
33 return levelStr;
34 }
35
36 }
0 package org.slf4j.event;
1
2 import org.slf4j.Marker;
3
4 /**
5 *
6 * @author ceki
7 * @since 1.7.15
8 */
9 public interface LoggingEvent {
10
11 Level getLevel();
12
13 Marker getMarker();
14
15 String getLoggerName();
16
17 String getMessage();
18
19 String getThreadName();
20
21 Object[] getArgumentArray();
22
23 long getTimeStamp();
24
25 Throwable getThrowable();
26
27 }
0 package org.slf4j.event;
1
2 import org.slf4j.Marker;
3
4 /**
5 *
6 * @author ceki
7 * @since 1.7.15
8 */
9 public interface LoggingEvent {
10
11 Level getLevel();
12
13 Marker getMarker();
14
15 String getLoggerName();
16
17 String getMessage();
18
19 String getThreadName();
20
21 Object[] getArgumentArray();
22
23 long getTimeStamp();
24
25 Throwable getThrowable();
26
27 }
0 package org.slf4j.event;
1
2 import org.slf4j.Marker;
3 import org.slf4j.helpers.SubstituteLogger;
4
5 public class SubstituteLoggingEvent implements LoggingEvent {
6
7 Level level;
8 Marker marker;
9 String loggerName;
10 SubstituteLogger logger;
11 String threadName;
12 String message;
13 Object[] argArray;
14 long timeStamp;
15 Throwable throwable;
16
17 public Level getLevel() {
18 return level;
19 }
20
21 public void setLevel(Level level) {
22 this.level = level;
23 }
24
25 public Marker getMarker() {
26 return marker;
27 }
28
29 public void setMarker(Marker marker) {
30 this.marker = marker;
31 }
32
33 public String getLoggerName() {
34 return loggerName;
35 }
36
37 public void setLoggerName(String loggerName) {
38 this.loggerName = loggerName;
39 }
40
41 public SubstituteLogger getLogger() {
42 return logger;
43 }
44
45 public void setLogger(SubstituteLogger logger) {
46 this.logger = logger;
47 }
48
49 public String getMessage() {
50 return message;
51 }
52
53 public void setMessage(String message) {
54 this.message = message;
55 }
56
57 public Object[] getArgumentArray() {
58 return argArray;
59 }
60
61 public void setArgumentArray(Object[] argArray) {
62 this.argArray = argArray;
63 }
64
65 public long getTimeStamp() {
66 return timeStamp;
67 }
68
69 public void setTimeStamp(long timeStamp) {
70 this.timeStamp = timeStamp;
71 }
72
73 public String getThreadName() {
74 return threadName;
75 }
76
77 public void setThreadName(String threadName) {
78 this.threadName = threadName;
79 }
80
81 public Throwable getThrowable() {
82 return throwable;
83 }
84
85 public void setThrowable(Throwable throwable) {
86 this.throwable = throwable;
87 }
88 }
0 package org.slf4j.event;
1
2 import org.slf4j.Marker;
3 import org.slf4j.helpers.SubstituteLogger;
4
5 public class SubstituteLoggingEvent implements LoggingEvent {
6
7 Level level;
8 Marker marker;
9 String loggerName;
10 SubstituteLogger logger;
11 String threadName;
12 String message;
13 Object[] argArray;
14 long timeStamp;
15 Throwable throwable;
16
17 public Level getLevel() {
18 return level;
19 }
20
21 public void setLevel(Level level) {
22 this.level = level;
23 }
24
25 public Marker getMarker() {
26 return marker;
27 }
28
29 public void setMarker(Marker marker) {
30 this.marker = marker;
31 }
32
33 public String getLoggerName() {
34 return loggerName;
35 }
36
37 public void setLoggerName(String loggerName) {
38 this.loggerName = loggerName;
39 }
40
41 public SubstituteLogger getLogger() {
42 return logger;
43 }
44
45 public void setLogger(SubstituteLogger logger) {
46 this.logger = logger;
47 }
48
49 public String getMessage() {
50 return message;
51 }
52
53 public void setMessage(String message) {
54 this.message = message;
55 }
56
57 public Object[] getArgumentArray() {
58 return argArray;
59 }
60
61 public void setArgumentArray(Object[] argArray) {
62 this.argArray = argArray;
63 }
64
65 public long getTimeStamp() {
66 return timeStamp;
67 }
68
69 public void setTimeStamp(long timeStamp) {
70 this.timeStamp = timeStamp;
71 }
72
73 public String getThreadName() {
74 return threadName;
75 }
76
77 public void setThreadName(String threadName) {
78 this.threadName = threadName;
79 }
80
81 public Throwable getThrowable() {
82 return throwable;
83 }
84
85 public void setThrowable(Throwable throwable) {
86 this.throwable = throwable;
87 }
88 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.spi.MDCAdapter;
27
28 import java.util.*;
29 import java.util.Map;
30
31 /**
32 * Basic MDC implementation, which can be used with logging systems that lack
33 * out-of-the-box MDC support.
34 *
35 * This code was initially inspired by logback's LogbackMDCAdapter. However,
36 * LogbackMDCAdapter has evolved and is now considerably more sophisticated.
37 *
38 * @author Ceki Gulcu
39 * @author Maarten Bosteels
40 * @author Lukasz Cwik
41 *
42 * @since 1.5.0
43 */
44 public class BasicMDCAdapter implements MDCAdapter {
45
46 private InheritableThreadLocal<Map<String, String>> inheritableThreadLocal = new InheritableThreadLocal<Map<String, String>>() {
47 @Override
48 protected Map<String, String> childValue(Map<String, String> parentValue) {
49 if (parentValue == null) {
50 return null;
51 }
52 return new HashMap<String, String>(parentValue);
53 }
54 };
55
56 /**
57 * Put a context value (the <code>val</code> parameter) as identified with
58 * the <code>key</code> parameter into the current thread's context map.
59 * Note that contrary to log4j, the <code>val</code> parameter can be null.
60 *
61 * <p>
62 * If the current thread does not have a context map it is created as a side
63 * effect of this call.
64 *
65 * @throws IllegalArgumentException
66 * in case the "key" parameter is null
67 */
68 public void put(String key, String val) {
69 if (key == null) {
70 throw new IllegalArgumentException("key cannot be null");
71 }
72 Map<String, String> map = inheritableThreadLocal.get();
73 if (map == null) {
74 map = new HashMap<String, String>();
75 inheritableThreadLocal.set(map);
76 }
77 map.put(key, val);
78 }
79
80 /**
81 * Get the context identified by the <code>key</code> parameter.
82 */
83 public String get(String key) {
84 Map<String, String> map = inheritableThreadLocal.get();
85 if ((map != null) && (key != null)) {
86 return map.get(key);
87 } else {
88 return null;
89 }
90 }
91
92 /**
93 * Remove the the context identified by the <code>key</code> parameter.
94 */
95 public void remove(String key) {
96 Map<String, String> map = inheritableThreadLocal.get();
97 if (map != null) {
98 map.remove(key);
99 }
100 }
101
102 /**
103 * Clear all entries in the MDC.
104 */
105 public void clear() {
106 Map<String, String> map = inheritableThreadLocal.get();
107 if (map != null) {
108 map.clear();
109 inheritableThreadLocal.remove();
110 }
111 }
112
113 /**
114 * Returns the keys in the MDC as a {@link Set} of {@link String}s The
115 * returned value can be null.
116 *
117 * @return the keys in the MDC
118 */
119 public Set<String> getKeys() {
120 Map<String, String> map = inheritableThreadLocal.get();
121 if (map != null) {
122 return map.keySet();
123 } else {
124 return null;
125 }
126 }
127
128 /**
129 * Return a copy of the current thread's context map.
130 * Returned value may be null.
131 *
132 */
133 public Map<String, String> getCopyOfContextMap() {
134 Map<String, String> oldMap = inheritableThreadLocal.get();
135 if (oldMap != null) {
136 return new HashMap<String, String>(oldMap);
137 } else {
138 return null;
139 }
140 }
141
142 public void setContextMap(Map<String, String> contextMap) {
143 inheritableThreadLocal.set(new HashMap<String, String>(contextMap));
144 }
145 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.spi.MDCAdapter;
27
28 import java.util.*;
29 import java.util.Map;
30
31 /**
32 * Basic MDC implementation, which can be used with logging systems that lack
33 * out-of-the-box MDC support.
34 *
35 * This code was initially inspired by logback's LogbackMDCAdapter. However,
36 * LogbackMDCAdapter has evolved and is now considerably more sophisticated.
37 *
38 * @author Ceki Gulcu
39 * @author Maarten Bosteels
40 * @author Lukasz Cwik
41 *
42 * @since 1.5.0
43 */
44 public class BasicMDCAdapter implements MDCAdapter {
45
46 private InheritableThreadLocal<Map<String, String>> inheritableThreadLocal = new InheritableThreadLocal<Map<String, String>>() {
47 @Override
48 protected Map<String, String> childValue(Map<String, String> parentValue) {
49 if (parentValue == null) {
50 return null;
51 }
52 return new HashMap<String, String>(parentValue);
53 }
54 };
55
56 /**
57 * Put a context value (the <code>val</code> parameter) as identified with
58 * the <code>key</code> parameter into the current thread's context map.
59 * Note that contrary to log4j, the <code>val</code> parameter can be null.
60 *
61 * <p>
62 * If the current thread does not have a context map it is created as a side
63 * effect of this call.
64 *
65 * @throws IllegalArgumentException
66 * in case the "key" parameter is null
67 */
68 public void put(String key, String val) {
69 if (key == null) {
70 throw new IllegalArgumentException("key cannot be null");
71 }
72 Map<String, String> map = inheritableThreadLocal.get();
73 if (map == null) {
74 map = new HashMap<String, String>();
75 inheritableThreadLocal.set(map);
76 }
77 map.put(key, val);
78 }
79
80 /**
81 * Get the context identified by the <code>key</code> parameter.
82 */
83 public String get(String key) {
84 Map<String, String> map = inheritableThreadLocal.get();
85 if ((map != null) && (key != null)) {
86 return map.get(key);
87 } else {
88 return null;
89 }
90 }
91
92 /**
93 * Remove the the context identified by the <code>key</code> parameter.
94 */
95 public void remove(String key) {
96 Map<String, String> map = inheritableThreadLocal.get();
97 if (map != null) {
98 map.remove(key);
99 }
100 }
101
102 /**
103 * Clear all entries in the MDC.
104 */
105 public void clear() {
106 Map<String, String> map = inheritableThreadLocal.get();
107 if (map != null) {
108 map.clear();
109 inheritableThreadLocal.remove();
110 }
111 }
112
113 /**
114 * Returns the keys in the MDC as a {@link Set} of {@link String}s The
115 * returned value can be null.
116 *
117 * @return the keys in the MDC
118 */
119 public Set<String> getKeys() {
120 Map<String, String> map = inheritableThreadLocal.get();
121 if (map != null) {
122 return map.keySet();
123 } else {
124 return null;
125 }
126 }
127
128 /**
129 * Return a copy of the current thread's context map.
130 * Returned value may be null.
131 *
132 */
133 public Map<String, String> getCopyOfContextMap() {
134 Map<String, String> oldMap = inheritableThreadLocal.get();
135 if (oldMap != null) {
136 return new HashMap<String, String>(oldMap);
137 } else {
138 return null;
139 }
140 }
141
142 public void setContextMap(Map<String, String> contextMap) {
143 inheritableThreadLocal.set(new HashMap<String, String>(contextMap));
144 }
145 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.concurrent.CopyOnWriteArrayList;
29
30 import org.slf4j.Marker;
31
32 /**
33 * A simple implementation of the {@link Marker} interface.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 * @author Joern Huxhorn
37 */
38 public class BasicMarker implements Marker {
39
40 private static final long serialVersionUID = -2849567615646933777L;
41 private final String name;
42 private List<Marker> referenceList = new CopyOnWriteArrayList<Marker>();
43
44 BasicMarker(String name) {
45 if (name == null) {
46 throw new IllegalArgumentException("A marker name cannot be null");
47 }
48 this.name = name;
49 }
50
51 public String getName() {
52 return name;
53 }
54
55 public void add(Marker reference) {
56 if (reference == null) {
57 throw new IllegalArgumentException("A null value cannot be added to a Marker as reference.");
58 }
59
60 // no point in adding the reference multiple times
61 if (this.contains(reference)) {
62 return;
63
64 } else if (reference.contains(this)) { // avoid recursion
65 // a potential reference should not hold its future "parent" as a reference
66 return;
67 } else {
68 referenceList.add(reference);
69 }
70 }
71
72 public boolean hasReferences() {
73 return (referenceList.size() > 0);
74 }
75
76 public boolean hasChildren() {
77 return hasReferences();
78 }
79
80 public Iterator<Marker> iterator() {
81 return referenceList.iterator();
82 }
83
84 public boolean remove(Marker referenceToRemove) {
85 return referenceList.remove(referenceToRemove);
86 }
87
88 public boolean contains(Marker other) {
89 if (other == null) {
90 throw new IllegalArgumentException("Other cannot be null");
91 }
92
93 if (this.equals(other)) {
94 return true;
95 }
96
97 if (hasReferences()) {
98 for (Marker ref : referenceList) {
99 if (ref.contains(other)) {
100 return true;
101 }
102 }
103 }
104 return false;
105 }
106
107 /**
108 * This method is mainly used with Expression Evaluators.
109 */
110 public boolean contains(String name) {
111 if (name == null) {
112 throw new IllegalArgumentException("Other cannot be null");
113 }
114
115 if (this.name.equals(name)) {
116 return true;
117 }
118
119 if (hasReferences()) {
120 for (Marker ref : referenceList) {
121 if (ref.contains(name)) {
122 return true;
123 }
124 }
125 }
126 return false;
127 }
128
129 private static String OPEN = "[ ";
130 private static String CLOSE = " ]";
131 private static String SEP = ", ";
132
133 public boolean equals(Object obj) {
134 if (this == obj)
135 return true;
136 if (obj == null)
137 return false;
138 if (!(obj instanceof Marker))
139 return false;
140
141 final Marker other = (Marker) obj;
142 return name.equals(other.getName());
143 }
144
145 public int hashCode() {
146 return name.hashCode();
147 }
148
149 public String toString() {
150 if (!this.hasReferences()) {
151 return this.getName();
152 }
153 Iterator<Marker> it = this.iterator();
154 Marker reference;
155 StringBuilder sb = new StringBuilder(this.getName());
156 sb.append(' ').append(OPEN);
157 while (it.hasNext()) {
158 reference = it.next();
159 sb.append(reference.getName());
160 if (it.hasNext()) {
161 sb.append(SEP);
162 }
163 }
164 sb.append(CLOSE);
165
166 return sb.toString();
167 }
168 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.concurrent.CopyOnWriteArrayList;
29
30 import org.slf4j.Marker;
31
32 /**
33 * A simple implementation of the {@link Marker} interface.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 * @author Joern Huxhorn
37 */
38 public class BasicMarker implements Marker {
39
40 private static final long serialVersionUID = -2849567615646933777L;
41 private final String name;
42 private List<Marker> referenceList = new CopyOnWriteArrayList<Marker>();
43
44 BasicMarker(String name) {
45 if (name == null) {
46 throw new IllegalArgumentException("A marker name cannot be null");
47 }
48 this.name = name;
49 }
50
51 public String getName() {
52 return name;
53 }
54
55 public void add(Marker reference) {
56 if (reference == null) {
57 throw new IllegalArgumentException("A null value cannot be added to a Marker as reference.");
58 }
59
60 // no point in adding the reference multiple times
61 if (this.contains(reference)) {
62 return;
63
64 } else if (reference.contains(this)) { // avoid recursion
65 // a potential reference should not hold its future "parent" as a reference
66 return;
67 } else {
68 referenceList.add(reference);
69 }
70 }
71
72 public boolean hasReferences() {
73 return (referenceList.size() > 0);
74 }
75
76 public boolean hasChildren() {
77 return hasReferences();
78 }
79
80 public Iterator<Marker> iterator() {
81 return referenceList.iterator();
82 }
83
84 public boolean remove(Marker referenceToRemove) {
85 return referenceList.remove(referenceToRemove);
86 }
87
88 public boolean contains(Marker other) {
89 if (other == null) {
90 throw new IllegalArgumentException("Other cannot be null");
91 }
92
93 if (this.equals(other)) {
94 return true;
95 }
96
97 if (hasReferences()) {
98 for (Marker ref : referenceList) {
99 if (ref.contains(other)) {
100 return true;
101 }
102 }
103 }
104 return false;
105 }
106
107 /**
108 * This method is mainly used with Expression Evaluators.
109 */
110 public boolean contains(String name) {
111 if (name == null) {
112 throw new IllegalArgumentException("Other cannot be null");
113 }
114
115 if (this.name.equals(name)) {
116 return true;
117 }
118
119 if (hasReferences()) {
120 for (Marker ref : referenceList) {
121 if (ref.contains(name)) {
122 return true;
123 }
124 }
125 }
126 return false;
127 }
128
129 private static String OPEN = "[ ";
130 private static String CLOSE = " ]";
131 private static String SEP = ", ";
132
133 public boolean equals(Object obj) {
134 if (this == obj)
135 return true;
136 if (obj == null)
137 return false;
138 if (!(obj instanceof Marker))
139 return false;
140
141 final Marker other = (Marker) obj;
142 return name.equals(other.getName());
143 }
144
145 public int hashCode() {
146 return name.hashCode();
147 }
148
149 public String toString() {
150 if (!this.hasReferences()) {
151 return this.getName();
152 }
153 Iterator<Marker> it = this.iterator();
154 Marker reference;
155 StringBuilder sb = new StringBuilder(this.getName());
156 sb.append(' ').append(OPEN);
157 while (it.hasNext()) {
158 reference = it.next();
159 sb.append(reference.getName());
160 if (it.hasNext()) {
161 sb.append(SEP);
162 }
163 }
164 sb.append(CLOSE);
165
166 return sb.toString();
167 }
168 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.slf4j.IMarkerFactory;
30 import org.slf4j.Marker;
31
32 /**
33 * An almost trivial implementation of the {@link IMarkerFactory}
34 * interface which creates {@link BasicMarker} instances.
35 *
36 * <p>Simple logging systems can conform to the SLF4J API by binding
37 * {@link org.slf4j.MarkerFactory} with an instance of this class.
38 *
39 * @author Ceki G&uuml;lc&uuml;
40 */
41 public class BasicMarkerFactory implements IMarkerFactory {
42
43 private final ConcurrentMap<String, Marker> markerMap = new ConcurrentHashMap<String, Marker>();
44
45 /**
46 * Regular users should <em>not</em> create
47 * <code>BasicMarkerFactory</code> instances. <code>Marker</code>
48 * instances can be obtained using the static {@link
49 * org.slf4j.MarkerFactory#getMarker} method.
50 */
51 public BasicMarkerFactory() {
52 }
53
54 /**
55 * Manufacture a {@link BasicMarker} instance by name. If the instance has been
56 * created earlier, return the previously created instance.
57 *
58 * @param name the name of the marker to be created
59 * @return a Marker instance
60 */
61 public Marker getMarker(String name) {
62 if (name == null) {
63 throw new IllegalArgumentException("Marker name cannot be null");
64 }
65
66 Marker marker = markerMap.get(name);
67 if (marker == null) {
68 marker = new BasicMarker(name);
69 Marker oldMarker = markerMap.putIfAbsent(name, marker);
70 if (oldMarker != null) {
71 marker = oldMarker;
72 }
73 }
74 return marker;
75 }
76
77 /**
78 * Does the name marked already exist?
79 */
80 public boolean exists(String name) {
81 if (name == null) {
82 return false;
83 }
84 return markerMap.containsKey(name);
85 }
86
87 public boolean detachMarker(String name) {
88 if (name == null) {
89 return false;
90 }
91 return (markerMap.remove(name) != null);
92 }
93
94 public Marker getDetachedMarker(String name) {
95 return new BasicMarker(name);
96 }
97
98 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.slf4j.IMarkerFactory;
30 import org.slf4j.Marker;
31
32 /**
33 * An almost trivial implementation of the {@link IMarkerFactory}
34 * interface which creates {@link BasicMarker} instances.
35 *
36 * <p>Simple logging systems can conform to the SLF4J API by binding
37 * {@link org.slf4j.MarkerFactory} with an instance of this class.
38 *
39 * @author Ceki G&uuml;lc&uuml;
40 */
41 public class BasicMarkerFactory implements IMarkerFactory {
42
43 private final ConcurrentMap<String, Marker> markerMap = new ConcurrentHashMap<String, Marker>();
44
45 /**
46 * Regular users should <em>not</em> create
47 * <code>BasicMarkerFactory</code> instances. <code>Marker</code>
48 * instances can be obtained using the static {@link
49 * org.slf4j.MarkerFactory#getMarker} method.
50 */
51 public BasicMarkerFactory() {
52 }
53
54 /**
55 * Manufacture a {@link BasicMarker} instance by name. If the instance has been
56 * created earlier, return the previously created instance.
57 *
58 * @param name the name of the marker to be created
59 * @return a Marker instance
60 */
61 public Marker getMarker(String name) {
62 if (name == null) {
63 throw new IllegalArgumentException("Marker name cannot be null");
64 }
65
66 Marker marker = markerMap.get(name);
67 if (marker == null) {
68 marker = new BasicMarker(name);
69 Marker oldMarker = markerMap.putIfAbsent(name, marker);
70 if (oldMarker != null) {
71 marker = oldMarker;
72 }
73 }
74 return marker;
75 }
76
77 /**
78 * Does the name marked already exist?
79 */
80 public boolean exists(String name) {
81 if (name == null) {
82 return false;
83 }
84 return markerMap.containsKey(name);
85 }
86
87 public boolean detachMarker(String name) {
88 if (name == null) {
89 return false;
90 }
91 return (markerMap.remove(name) != null);
92 }
93
94 public Marker getDetachedMarker(String name) {
95 return new BasicMarker(name);
96 }
97
98 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 /**
27 * Holds the results of formatting done by {@link MessageFormatter}.
28 *
29 * @author Joern Huxhorn
30 */
31 public class FormattingTuple {
32
33 static public FormattingTuple NULL = new FormattingTuple(null);
34
35 private String message;
36 private Throwable throwable;
37 private Object[] argArray;
38
39 public FormattingTuple(String message) {
40 this(message, null, null);
41 }
42
43 public FormattingTuple(String message, Object[] argArray, Throwable throwable) {
44 this.message = message;
45 this.throwable = throwable;
46 this.argArray = argArray;
47 }
48
49 public String getMessage() {
50 return message;
51 }
52
53 public Object[] getArgArray() {
54 return argArray;
55 }
56
57 public Throwable getThrowable() {
58 return throwable;
59 }
60
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 /**
27 * Holds the results of formatting done by {@link MessageFormatter}.
28 *
29 * @author Joern Huxhorn
30 */
31 public class FormattingTuple {
32
33 static public FormattingTuple NULL = new FormattingTuple(null);
34
35 private String message;
36 private Throwable throwable;
37 private Object[] argArray;
38
39 public FormattingTuple(String message) {
40 this(message, null, null);
41 }
42
43 public FormattingTuple(String message, Object[] argArray, Throwable throwable) {
44 this.message = message;
45 this.throwable = throwable;
46 this.argArray = argArray;
47 }
48
49 public String getMessage() {
50 return message;
51 }
52
53 public Object[] getArgArray() {
54 return argArray;
55 }
56
57 public Throwable getThrowable() {
58 return throwable;
59 }
60
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28
29 /**
30 * This class serves as base for adapters or native implementations of logging systems
31 * lacking Marker support. In this implementation, methods taking marker data
32 * simply invoke the corresponding method without the Marker argument, discarding
33 * any marker data passed as argument.
34 *
35 * @author Ceki Gulcu
36 */
37 public abstract class MarkerIgnoringBase extends NamedLoggerBase implements Logger {
38
39 private static final long serialVersionUID = 9044267456635152283L;
40
41 public boolean isTraceEnabled(Marker marker) {
42 return isTraceEnabled();
43 }
44
45 public void trace(Marker marker, String msg) {
46 trace(msg);
47 }
48
49 public void trace(Marker marker, String format, Object arg) {
50 trace(format, arg);
51 }
52
53 public void trace(Marker marker, String format, Object arg1, Object arg2) {
54 trace(format, arg1, arg2);
55 }
56
57 public void trace(Marker marker, String format, Object... arguments) {
58 trace(format, arguments);
59 }
60
61 public void trace(Marker marker, String msg, Throwable t) {
62 trace(msg, t);
63 }
64
65 public boolean isDebugEnabled(Marker marker) {
66 return isDebugEnabled();
67 }
68
69 public void debug(Marker marker, String msg) {
70 debug(msg);
71 }
72
73 public void debug(Marker marker, String format, Object arg) {
74 debug(format, arg);
75 }
76
77 public void debug(Marker marker, String format, Object arg1, Object arg2) {
78 debug(format, arg1, arg2);
79 }
80
81 public void debug(Marker marker, String format, Object... arguments) {
82 debug(format, arguments);
83 }
84
85 public void debug(Marker marker, String msg, Throwable t) {
86 debug(msg, t);
87 }
88
89 public boolean isInfoEnabled(Marker marker) {
90 return isInfoEnabled();
91 }
92
93 public void info(Marker marker, String msg) {
94 info(msg);
95 }
96
97 public void info(Marker marker, String format, Object arg) {
98 info(format, arg);
99 }
100
101 public void info(Marker marker, String format, Object arg1, Object arg2) {
102 info(format, arg1, arg2);
103 }
104
105 public void info(Marker marker, String format, Object... arguments) {
106 info(format, arguments);
107 }
108
109 public void info(Marker marker, String msg, Throwable t) {
110 info(msg, t);
111 }
112
113 public boolean isWarnEnabled(Marker marker) {
114 return isWarnEnabled();
115 }
116
117 public void warn(Marker marker, String msg) {
118 warn(msg);
119 }
120
121 public void warn(Marker marker, String format, Object arg) {
122 warn(format, arg);
123 }
124
125 public void warn(Marker marker, String format, Object arg1, Object arg2) {
126 warn(format, arg1, arg2);
127 }
128
129 public void warn(Marker marker, String format, Object... arguments) {
130 warn(format, arguments);
131 }
132
133 public void warn(Marker marker, String msg, Throwable t) {
134 warn(msg, t);
135 }
136
137 public boolean isErrorEnabled(Marker marker) {
138 return isErrorEnabled();
139 }
140
141 public void error(Marker marker, String msg) {
142 error(msg);
143 }
144
145 public void error(Marker marker, String format, Object arg) {
146 error(format, arg);
147 }
148
149 public void error(Marker marker, String format, Object arg1, Object arg2) {
150 error(format, arg1, arg2);
151 }
152
153 public void error(Marker marker, String format, Object... arguments) {
154 error(format, arguments);
155 }
156
157 public void error(Marker marker, String msg, Throwable t) {
158 error(msg, t);
159 }
160
161 public String toString() {
162 return this.getClass().getName() + "(" + getName() + ")";
163 }
164
165 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28
29 /**
30 * This class serves as base for adapters or native implementations of logging systems
31 * lacking Marker support. In this implementation, methods taking marker data
32 * simply invoke the corresponding method without the Marker argument, discarding
33 * any marker data passed as argument.
34 *
35 * @author Ceki Gulcu
36 */
37 public abstract class MarkerIgnoringBase extends NamedLoggerBase implements Logger {
38
39 private static final long serialVersionUID = 9044267456635152283L;
40
41 public boolean isTraceEnabled(Marker marker) {
42 return isTraceEnabled();
43 }
44
45 public void trace(Marker marker, String msg) {
46 trace(msg);
47 }
48
49 public void trace(Marker marker, String format, Object arg) {
50 trace(format, arg);
51 }
52
53 public void trace(Marker marker, String format, Object arg1, Object arg2) {
54 trace(format, arg1, arg2);
55 }
56
57 public void trace(Marker marker, String format, Object... arguments) {
58 trace(format, arguments);
59 }
60
61 public void trace(Marker marker, String msg, Throwable t) {
62 trace(msg, t);
63 }
64
65 public boolean isDebugEnabled(Marker marker) {
66 return isDebugEnabled();
67 }
68
69 public void debug(Marker marker, String msg) {
70 debug(msg);
71 }
72
73 public void debug(Marker marker, String format, Object arg) {
74 debug(format, arg);
75 }
76
77 public void debug(Marker marker, String format, Object arg1, Object arg2) {
78 debug(format, arg1, arg2);
79 }
80
81 public void debug(Marker marker, String format, Object... arguments) {
82 debug(format, arguments);
83 }
84
85 public void debug(Marker marker, String msg, Throwable t) {
86 debug(msg, t);
87 }
88
89 public boolean isInfoEnabled(Marker marker) {
90 return isInfoEnabled();
91 }
92
93 public void info(Marker marker, String msg) {
94 info(msg);
95 }
96
97 public void info(Marker marker, String format, Object arg) {
98 info(format, arg);
99 }
100
101 public void info(Marker marker, String format, Object arg1, Object arg2) {
102 info(format, arg1, arg2);
103 }
104
105 public void info(Marker marker, String format, Object... arguments) {
106 info(format, arguments);
107 }
108
109 public void info(Marker marker, String msg, Throwable t) {
110 info(msg, t);
111 }
112
113 public boolean isWarnEnabled(Marker marker) {
114 return isWarnEnabled();
115 }
116
117 public void warn(Marker marker, String msg) {
118 warn(msg);
119 }
120
121 public void warn(Marker marker, String format, Object arg) {
122 warn(format, arg);
123 }
124
125 public void warn(Marker marker, String format, Object arg1, Object arg2) {
126 warn(format, arg1, arg2);
127 }
128
129 public void warn(Marker marker, String format, Object... arguments) {
130 warn(format, arguments);
131 }
132
133 public void warn(Marker marker, String msg, Throwable t) {
134 warn(msg, t);
135 }
136
137 public boolean isErrorEnabled(Marker marker) {
138 return isErrorEnabled();
139 }
140
141 public void error(Marker marker, String msg) {
142 error(msg);
143 }
144
145 public void error(Marker marker, String format, Object arg) {
146 error(format, arg);
147 }
148
149 public void error(Marker marker, String format, Object arg1, Object arg2) {
150 error(format, arg1, arg2);
151 }
152
153 public void error(Marker marker, String format, Object... arguments) {
154 error(format, arguments);
155 }
156
157 public void error(Marker marker, String msg, Throwable t) {
158 error(msg, t);
159 }
160
161 public String toString() {
162 return this.getClass().getName() + "(" + getName() + ")";
163 }
164
165 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.text.MessageFormat;
27 import java.util.HashMap;
28 import java.util.Map;
29
30 // contributors: lizongbo: proposed special treatment of array parameter values
31 // Joern Huxhorn: pointed out double[] omission, suggested deep array copy
32 /**
33 * Formats messages according to very simple substitution rules. Substitutions
34 * can be made 1, 2 or more arguments.
35 *
36 * <p>
37 * For example,
38 *
39 * <pre>
40 * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;)
41 * </pre>
42 *
43 * will return the string "Hi there.".
44 * <p>
45 * The {} pair is called the <em>formatting anchor</em>. It serves to designate
46 * the location where arguments need to be substituted within the message
47 * pattern.
48 * <p>
49 * In case your message contains the '{' or the '}' character, you do not have
50 * to do anything special unless the '}' character immediately follows '{'. For
51 * example,
52 *
53 * <pre>
54 * MessageFormatter.format(&quot;Set {1,2,3} is not equal to {}.&quot;, &quot;1,2&quot;);
55 * </pre>
56 *
57 * will return the string "Set {1,2,3} is not equal to 1,2.".
58 *
59 * <p>
60 * If for whatever reason you need to place the string "{}" in the message
61 * without its <em>formatting anchor</em> meaning, then you need to escape the
62 * '{' character with '\', that is the backslash character. Only the '{'
63 * character should be escaped. There is no need to escape the '}' character.
64 * For example,
65 *
66 * <pre>
67 * MessageFormatter.format(&quot;Set \\{} is not equal to {}.&quot;, &quot;1,2&quot;);
68 * </pre>
69 *
70 * will return the string "Set {} is not equal to 1,2.".
71 *
72 * <p>
73 * The escaping behavior just described can be overridden by escaping the escape
74 * character '\'. Calling
75 *
76 * <pre>
77 * MessageFormatter.format(&quot;File name is C:\\\\{}.&quot;, &quot;file.zip&quot;);
78 * </pre>
79 *
80 * will return the string "File name is C:\file.zip".
81 *
82 * <p>
83 * The formatting conventions are different than those of {@link MessageFormat}
84 * which ships with the Java platform. This is justified by the fact that
85 * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}.
86 * This local performance difference is both measurable and significant in the
87 * larger context of the complete logging processing chain.
88 *
89 * <p>
90 * See also {@link #format(String, Object)},
91 * {@link #format(String, Object, Object)} and
92 * {@link #arrayFormat(String, Object[])} methods for more details.
93 *
94 * @author Ceki G&uuml;lc&uuml;
95 * @author Joern Huxhorn
96 */
97 final public class MessageFormatter {
98 static final char DELIM_START = '{';
99 static final char DELIM_STOP = '}';
100 static final String DELIM_STR = "{}";
101 private static final char ESCAPE_CHAR = '\\';
102
103 /**
104 * Performs single argument substitution for the 'messagePattern' passed as
105 * parameter.
106 * <p>
107 * For example,
108 *
109 * <pre>
110 * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;);
111 * </pre>
112 *
113 * will return the string "Hi there.".
114 * <p>
115 *
116 * @param messagePattern
117 * The message pattern which will be parsed and formatted
118 * @param arg
119 * The argument to be substituted in place of the formatting anchor
120 * @return The formatted message
121 */
122 final public static FormattingTuple format(String messagePattern, Object arg) {
123 return arrayFormat(messagePattern, new Object[] { arg });
124 }
125
126 /**
127 *
128 * Performs a two argument substitution for the 'messagePattern' passed as
129 * parameter.
130 * <p>
131 * For example,
132 *
133 * <pre>
134 * MessageFormatter.format(&quot;Hi {}. My name is {}.&quot;, &quot;Alice&quot;, &quot;Bob&quot;);
135 * </pre>
136 *
137 * will return the string "Hi Alice. My name is Bob.".
138 *
139 * @param messagePattern
140 * The message pattern which will be parsed and formatted
141 * @param arg1
142 * The argument to be substituted in place of the first formatting
143 * anchor
144 * @param arg2
145 * The argument to be substituted in place of the second formatting
146 * anchor
147 * @return The formatted message
148 */
149 final public static FormattingTuple format(final String messagePattern, Object arg1, Object arg2) {
150 return arrayFormat(messagePattern, new Object[] { arg1, arg2 });
151 }
152
153
154 static final Throwable getThrowableCandidate(Object[] argArray) {
155 if (argArray == null || argArray.length == 0) {
156 return null;
157 }
158
159 final Object lastEntry = argArray[argArray.length - 1];
160 if (lastEntry instanceof Throwable) {
161 return (Throwable) lastEntry;
162 }
163 return null;
164 }
165
166 final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) {
167 Throwable throwableCandidate = getThrowableCandidate(argArray);
168 Object[] args = argArray;
169 if (throwableCandidate != null) {
170 args = trimmedCopy(argArray);
171 }
172 return arrayFormat(messagePattern, args, throwableCandidate);
173 }
174
175 private static Object[] trimmedCopy(Object[] argArray) {
176 if (argArray == null || argArray.length == 0) {
177 throw new IllegalStateException("non-sensical empty or null argument array");
178 }
179 final int trimemdLen = argArray.length - 1;
180 Object[] trimmed = new Object[trimemdLen];
181 System.arraycopy(argArray, 0, trimmed, 0, trimemdLen);
182 return trimmed;
183 }
184
185 final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray, Throwable throwable) {
186
187 if (messagePattern == null) {
188 return new FormattingTuple(null, argArray, throwable);
189 }
190
191 if (argArray == null) {
192 return new FormattingTuple(messagePattern);
193 }
194
195 int i = 0;
196 int j;
197 // use string builder for better multicore performance
198 StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50);
199
200 int L;
201 for (L = 0; L < argArray.length; L++) {
202
203 j = messagePattern.indexOf(DELIM_STR, i);
204
205 if (j == -1) {
206 // no more variables
207 if (i == 0) { // this is a simple string
208 return new FormattingTuple(messagePattern, argArray, throwable);
209 } else { // add the tail string which contains no variables and return
210 // the result.
211 sbuf.append(messagePattern, i, messagePattern.length());
212 return new FormattingTuple(sbuf.toString(), argArray, throwable);
213 }
214 } else {
215 if (isEscapedDelimeter(messagePattern, j)) {
216 if (!isDoubleEscaped(messagePattern, j)) {
217 L--; // DELIM_START was escaped, thus should not be incremented
218 sbuf.append(messagePattern, i, j - 1);
219 sbuf.append(DELIM_START);
220 i = j + 1;
221 } else {
222 // The escape character preceding the delimiter start is
223 // itself escaped: "abc x:\\{}"
224 // we have to consume one backward slash
225 sbuf.append(messagePattern, i, j - 1);
226 deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
227 i = j + 2;
228 }
229 } else {
230 // normal case
231 sbuf.append(messagePattern, i, j);
232 deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
233 i = j + 2;
234 }
235 }
236 }
237 // append the characters following the last {} pair.
238 sbuf.append(messagePattern, i, messagePattern.length());
239 return new FormattingTuple(sbuf.toString(), argArray, throwable);
240 }
241
242 final static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) {
243
244 if (delimeterStartIndex == 0) {
245 return false;
246 }
247 char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1);
248 if (potentialEscape == ESCAPE_CHAR) {
249 return true;
250 } else {
251 return false;
252 }
253 }
254
255 final static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) {
256 if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) {
257 return true;
258 } else {
259 return false;
260 }
261 }
262
263 // special treatment of array values was suggested by 'lizongbo'
264 private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Map<Object[], Object> seenMap) {
265 if (o == null) {
266 sbuf.append("null");
267 return;
268 }
269 if (!o.getClass().isArray()) {
270 safeObjectAppend(sbuf, o);
271 } else {
272 // check for primitive array types because they
273 // unfortunately cannot be cast to Object[]
274 if (o instanceof boolean[]) {
275 booleanArrayAppend(sbuf, (boolean[]) o);
276 } else if (o instanceof byte[]) {
277 byteArrayAppend(sbuf, (byte[]) o);
278 } else if (o instanceof char[]) {
279 charArrayAppend(sbuf, (char[]) o);
280 } else if (o instanceof short[]) {
281 shortArrayAppend(sbuf, (short[]) o);
282 } else if (o instanceof int[]) {
283 intArrayAppend(sbuf, (int[]) o);
284 } else if (o instanceof long[]) {
285 longArrayAppend(sbuf, (long[]) o);
286 } else if (o instanceof float[]) {
287 floatArrayAppend(sbuf, (float[]) o);
288 } else if (o instanceof double[]) {
289 doubleArrayAppend(sbuf, (double[]) o);
290 } else {
291 objectArrayAppend(sbuf, (Object[]) o, seenMap);
292 }
293 }
294 }
295
296 private static void safeObjectAppend(StringBuilder sbuf, Object o) {
297 try {
298 String oAsString = o.toString();
299 sbuf.append(oAsString);
300 } catch (Throwable t) {
301 Util.report("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]", t);
302 sbuf.append("[FAILED toString()]");
303 }
304
305 }
306
307 private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map<Object[], Object> seenMap) {
308 sbuf.append('[');
309 if (!seenMap.containsKey(a)) {
310 seenMap.put(a, null);
311 final int len = a.length;
312 for (int i = 0; i < len; i++) {
313 deeplyAppendParameter(sbuf, a[i], seenMap);
314 if (i != len - 1)
315 sbuf.append(", ");
316 }
317 // allow repeats in siblings
318 seenMap.remove(a);
319 } else {
320 sbuf.append("...");
321 }
322 sbuf.append(']');
323 }
324
325 private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) {
326 sbuf.append('[');
327 final int len = a.length;
328 for (int i = 0; i < len; i++) {
329 sbuf.append(a[i]);
330 if (i != len - 1)
331 sbuf.append(", ");
332 }
333 sbuf.append(']');
334 }
335
336 private static void byteArrayAppend(StringBuilder sbuf, byte[] a) {
337 sbuf.append('[');
338 final int len = a.length;
339 for (int i = 0; i < len; i++) {
340 sbuf.append(a[i]);
341 if (i != len - 1)
342 sbuf.append(", ");
343 }
344 sbuf.append(']');
345 }
346
347 private static void charArrayAppend(StringBuilder sbuf, char[] a) {
348 sbuf.append('[');
349 final int len = a.length;
350 for (int i = 0; i < len; i++) {
351 sbuf.append(a[i]);
352 if (i != len - 1)
353 sbuf.append(", ");
354 }
355 sbuf.append(']');
356 }
357
358 private static void shortArrayAppend(StringBuilder sbuf, short[] a) {
359 sbuf.append('[');
360 final int len = a.length;
361 for (int i = 0; i < len; i++) {
362 sbuf.append(a[i]);
363 if (i != len - 1)
364 sbuf.append(", ");
365 }
366 sbuf.append(']');
367 }
368
369 private static void intArrayAppend(StringBuilder sbuf, int[] a) {
370 sbuf.append('[');
371 final int len = a.length;
372 for (int i = 0; i < len; i++) {
373 sbuf.append(a[i]);
374 if (i != len - 1)
375 sbuf.append(", ");
376 }
377 sbuf.append(']');
378 }
379
380 private static void longArrayAppend(StringBuilder sbuf, long[] a) {
381 sbuf.append('[');
382 final int len = a.length;
383 for (int i = 0; i < len; i++) {
384 sbuf.append(a[i]);
385 if (i != len - 1)
386 sbuf.append(", ");
387 }
388 sbuf.append(']');
389 }
390
391 private static void floatArrayAppend(StringBuilder sbuf, float[] a) {
392 sbuf.append('[');
393 final int len = a.length;
394 for (int i = 0; i < len; i++) {
395 sbuf.append(a[i]);
396 if (i != len - 1)
397 sbuf.append(", ");
398 }
399 sbuf.append(']');
400 }
401
402 private static void doubleArrayAppend(StringBuilder sbuf, double[] a) {
403 sbuf.append('[');
404 final int len = a.length;
405 for (int i = 0; i < len; i++) {
406 sbuf.append(a[i]);
407 if (i != len - 1)
408 sbuf.append(", ");
409 }
410 sbuf.append(']');
411 }
412
413 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.text.MessageFormat;
27 import java.util.HashMap;
28 import java.util.Map;
29
30 // contributors: lizongbo: proposed special treatment of array parameter values
31 // Joern Huxhorn: pointed out double[] omission, suggested deep array copy
32 /**
33 * Formats messages according to very simple substitution rules. Substitutions
34 * can be made 1, 2 or more arguments.
35 *
36 * <p>
37 * For example,
38 *
39 * <pre>
40 * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;)
41 * </pre>
42 *
43 * will return the string "Hi there.".
44 * <p>
45 * The {} pair is called the <em>formatting anchor</em>. It serves to designate
46 * the location where arguments need to be substituted within the message
47 * pattern.
48 * <p>
49 * In case your message contains the '{' or the '}' character, you do not have
50 * to do anything special unless the '}' character immediately follows '{'. For
51 * example,
52 *
53 * <pre>
54 * MessageFormatter.format(&quot;Set {1,2,3} is not equal to {}.&quot;, &quot;1,2&quot;);
55 * </pre>
56 *
57 * will return the string "Set {1,2,3} is not equal to 1,2.".
58 *
59 * <p>
60 * If for whatever reason you need to place the string "{}" in the message
61 * without its <em>formatting anchor</em> meaning, then you need to escape the
62 * '{' character with '\', that is the backslash character. Only the '{'
63 * character should be escaped. There is no need to escape the '}' character.
64 * For example,
65 *
66 * <pre>
67 * MessageFormatter.format(&quot;Set \\{} is not equal to {}.&quot;, &quot;1,2&quot;);
68 * </pre>
69 *
70 * will return the string "Set {} is not equal to 1,2.".
71 *
72 * <p>
73 * The escaping behavior just described can be overridden by escaping the escape
74 * character '\'. Calling
75 *
76 * <pre>
77 * MessageFormatter.format(&quot;File name is C:\\\\{}.&quot;, &quot;file.zip&quot;);
78 * </pre>
79 *
80 * will return the string "File name is C:\file.zip".
81 *
82 * <p>
83 * The formatting conventions are different than those of {@link MessageFormat}
84 * which ships with the Java platform. This is justified by the fact that
85 * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}.
86 * This local performance difference is both measurable and significant in the
87 * larger context of the complete logging processing chain.
88 *
89 * <p>
90 * See also {@link #format(String, Object)},
91 * {@link #format(String, Object, Object)} and
92 * {@link #arrayFormat(String, Object[])} methods for more details.
93 *
94 * @author Ceki G&uuml;lc&uuml;
95 * @author Joern Huxhorn
96 */
97 final public class MessageFormatter {
98 static final char DELIM_START = '{';
99 static final char DELIM_STOP = '}';
100 static final String DELIM_STR = "{}";
101 private static final char ESCAPE_CHAR = '\\';
102
103 /**
104 * Performs single argument substitution for the 'messagePattern' passed as
105 * parameter.
106 * <p>
107 * For example,
108 *
109 * <pre>
110 * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;);
111 * </pre>
112 *
113 * will return the string "Hi there.".
114 * <p>
115 *
116 * @param messagePattern
117 * The message pattern which will be parsed and formatted
118 * @param arg
119 * The argument to be substituted in place of the formatting anchor
120 * @return The formatted message
121 */
122 final public static FormattingTuple format(String messagePattern, Object arg) {
123 return arrayFormat(messagePattern, new Object[] { arg });
124 }
125
126 /**
127 *
128 * Performs a two argument substitution for the 'messagePattern' passed as
129 * parameter.
130 * <p>
131 * For example,
132 *
133 * <pre>
134 * MessageFormatter.format(&quot;Hi {}. My name is {}.&quot;, &quot;Alice&quot;, &quot;Bob&quot;);
135 * </pre>
136 *
137 * will return the string "Hi Alice. My name is Bob.".
138 *
139 * @param messagePattern
140 * The message pattern which will be parsed and formatted
141 * @param arg1
142 * The argument to be substituted in place of the first formatting
143 * anchor
144 * @param arg2
145 * The argument to be substituted in place of the second formatting
146 * anchor
147 * @return The formatted message
148 */
149 final public static FormattingTuple format(final String messagePattern, Object arg1, Object arg2) {
150 return arrayFormat(messagePattern, new Object[] { arg1, arg2 });
151 }
152
153
154 static final Throwable getThrowableCandidate(Object[] argArray) {
155 if (argArray == null || argArray.length == 0) {
156 return null;
157 }
158
159 final Object lastEntry = argArray[argArray.length - 1];
160 if (lastEntry instanceof Throwable) {
161 return (Throwable) lastEntry;
162 }
163 return null;
164 }
165
166 final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) {
167 Throwable throwableCandidate = getThrowableCandidate(argArray);
168 Object[] args = argArray;
169 if (throwableCandidate != null) {
170 args = trimmedCopy(argArray);
171 }
172 return arrayFormat(messagePattern, args, throwableCandidate);
173 }
174
175 private static Object[] trimmedCopy(Object[] argArray) {
176 if (argArray == null || argArray.length == 0) {
177 throw new IllegalStateException("non-sensical empty or null argument array");
178 }
179 final int trimemdLen = argArray.length - 1;
180 Object[] trimmed = new Object[trimemdLen];
181 System.arraycopy(argArray, 0, trimmed, 0, trimemdLen);
182 return trimmed;
183 }
184
185 final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray, Throwable throwable) {
186
187 if (messagePattern == null) {
188 return new FormattingTuple(null, argArray, throwable);
189 }
190
191 if (argArray == null) {
192 return new FormattingTuple(messagePattern);
193 }
194
195 int i = 0;
196 int j;
197 // use string builder for better multicore performance
198 StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50);
199
200 int L;
201 for (L = 0; L < argArray.length; L++) {
202
203 j = messagePattern.indexOf(DELIM_STR, i);
204
205 if (j == -1) {
206 // no more variables
207 if (i == 0) { // this is a simple string
208 return new FormattingTuple(messagePattern, argArray, throwable);
209 } else { // add the tail string which contains no variables and return
210 // the result.
211 sbuf.append(messagePattern, i, messagePattern.length());
212 return new FormattingTuple(sbuf.toString(), argArray, throwable);
213 }
214 } else {
215 if (isEscapedDelimeter(messagePattern, j)) {
216 if (!isDoubleEscaped(messagePattern, j)) {
217 L--; // DELIM_START was escaped, thus should not be incremented
218 sbuf.append(messagePattern, i, j - 1);
219 sbuf.append(DELIM_START);
220 i = j + 1;
221 } else {
222 // The escape character preceding the delimiter start is
223 // itself escaped: "abc x:\\{}"
224 // we have to consume one backward slash
225 sbuf.append(messagePattern, i, j - 1);
226 deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
227 i = j + 2;
228 }
229 } else {
230 // normal case
231 sbuf.append(messagePattern, i, j);
232 deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
233 i = j + 2;
234 }
235 }
236 }
237 // append the characters following the last {} pair.
238 sbuf.append(messagePattern, i, messagePattern.length());
239 return new FormattingTuple(sbuf.toString(), argArray, throwable);
240 }
241
242 final static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) {
243
244 if (delimeterStartIndex == 0) {
245 return false;
246 }
247 char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1);
248 if (potentialEscape == ESCAPE_CHAR) {
249 return true;
250 } else {
251 return false;
252 }
253 }
254
255 final static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) {
256 if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) {
257 return true;
258 } else {
259 return false;
260 }
261 }
262
263 // special treatment of array values was suggested by 'lizongbo'
264 private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Map<Object[], Object> seenMap) {
265 if (o == null) {
266 sbuf.append("null");
267 return;
268 }
269 if (!o.getClass().isArray()) {
270 safeObjectAppend(sbuf, o);
271 } else {
272 // check for primitive array types because they
273 // unfortunately cannot be cast to Object[]
274 if (o instanceof boolean[]) {
275 booleanArrayAppend(sbuf, (boolean[]) o);
276 } else if (o instanceof byte[]) {
277 byteArrayAppend(sbuf, (byte[]) o);
278 } else if (o instanceof char[]) {
279 charArrayAppend(sbuf, (char[]) o);
280 } else if (o instanceof short[]) {
281 shortArrayAppend(sbuf, (short[]) o);
282 } else if (o instanceof int[]) {
283 intArrayAppend(sbuf, (int[]) o);
284 } else if (o instanceof long[]) {
285 longArrayAppend(sbuf, (long[]) o);
286 } else if (o instanceof float[]) {
287 floatArrayAppend(sbuf, (float[]) o);
288 } else if (o instanceof double[]) {
289 doubleArrayAppend(sbuf, (double[]) o);
290 } else {
291 objectArrayAppend(sbuf, (Object[]) o, seenMap);
292 }
293 }
294 }
295
296 private static void safeObjectAppend(StringBuilder sbuf, Object o) {
297 try {
298 String oAsString = o.toString();
299 sbuf.append(oAsString);
300 } catch (Throwable t) {
301 Util.report("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]", t);
302 sbuf.append("[FAILED toString()]");
303 }
304
305 }
306
307 private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map<Object[], Object> seenMap) {
308 sbuf.append('[');
309 if (!seenMap.containsKey(a)) {
310 seenMap.put(a, null);
311 final int len = a.length;
312 for (int i = 0; i < len; i++) {
313 deeplyAppendParameter(sbuf, a[i], seenMap);
314 if (i != len - 1)
315 sbuf.append(", ");
316 }
317 // allow repeats in siblings
318 seenMap.remove(a);
319 } else {
320 sbuf.append("...");
321 }
322 sbuf.append(']');
323 }
324
325 private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) {
326 sbuf.append('[');
327 final int len = a.length;
328 for (int i = 0; i < len; i++) {
329 sbuf.append(a[i]);
330 if (i != len - 1)
331 sbuf.append(", ");
332 }
333 sbuf.append(']');
334 }
335
336 private static void byteArrayAppend(StringBuilder sbuf, byte[] a) {
337 sbuf.append('[');
338 final int len = a.length;
339 for (int i = 0; i < len; i++) {
340 sbuf.append(a[i]);
341 if (i != len - 1)
342 sbuf.append(", ");
343 }
344 sbuf.append(']');
345 }
346
347 private static void charArrayAppend(StringBuilder sbuf, char[] a) {
348 sbuf.append('[');
349 final int len = a.length;
350 for (int i = 0; i < len; i++) {
351 sbuf.append(a[i]);
352 if (i != len - 1)
353 sbuf.append(", ");
354 }
355 sbuf.append(']');
356 }
357
358 private static void shortArrayAppend(StringBuilder sbuf, short[] a) {
359 sbuf.append('[');
360 final int len = a.length;
361 for (int i = 0; i < len; i++) {
362 sbuf.append(a[i]);
363 if (i != len - 1)
364 sbuf.append(", ");
365 }
366 sbuf.append(']');
367 }
368
369 private static void intArrayAppend(StringBuilder sbuf, int[] a) {
370 sbuf.append('[');
371 final int len = a.length;
372 for (int i = 0; i < len; i++) {
373 sbuf.append(a[i]);
374 if (i != len - 1)
375 sbuf.append(", ");
376 }
377 sbuf.append(']');
378 }
379
380 private static void longArrayAppend(StringBuilder sbuf, long[] a) {
381 sbuf.append('[');
382 final int len = a.length;
383 for (int i = 0; i < len; i++) {
384 sbuf.append(a[i]);
385 if (i != len - 1)
386 sbuf.append(", ");
387 }
388 sbuf.append(']');
389 }
390
391 private static void floatArrayAppend(StringBuilder sbuf, float[] a) {
392 sbuf.append('[');
393 final int len = a.length;
394 for (int i = 0; i < len; i++) {
395 sbuf.append(a[i]);
396 if (i != len - 1)
397 sbuf.append(", ");
398 }
399 sbuf.append(']');
400 }
401
402 private static void doubleArrayAppend(StringBuilder sbuf, double[] a) {
403 sbuf.append('[');
404 final int len = a.length;
405 for (int i = 0; i < len; i++) {
406 sbuf.append(a[i]);
407 if (i != len - 1)
408 sbuf.append(", ");
409 }
410 sbuf.append(']');
411 }
412
413 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.Logger;
27 import org.slf4j.helpers.MarkerIgnoringBase;
28
29 /**
30 * A direct NOP (no operation) implementation of {@link Logger}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class NOPLogger extends MarkerIgnoringBase {
35
36 private static final long serialVersionUID = -517220405410904473L;
37
38 /**
39 * The unique instance of NOPLogger.
40 */
41 public static final NOPLogger NOP_LOGGER = new NOPLogger();
42
43 /**
44 * There is no point in creating multiple instances of NOPLogger,
45 * except by derived classes, hence the protected access for the constructor.
46 */
47 protected NOPLogger() {
48 }
49
50 /**
51 * Always returns the string value "NOP".
52 */
53 public String getName() {
54 return "NOP";
55 }
56
57 /**
58 * Always returns false.
59 * @return always false
60 */
61 final public boolean isTraceEnabled() {
62 return false;
63 }
64
65 /** A NOP implementation. */
66 final public void trace(String msg) {
67 // NOP
68 }
69
70 /** A NOP implementation. */
71 final public void trace(String format, Object arg) {
72 // NOP
73 }
74
75 /** A NOP implementation. */
76 public final void trace(String format, Object arg1, Object arg2) {
77 // NOP
78 }
79
80 /** A NOP implementation. */
81 public final void trace(String format, Object... argArray) {
82 // NOP
83 }
84
85 /** A NOP implementation. */
86 final public void trace(String msg, Throwable t) {
87 // NOP
88 }
89
90 /**
91 * Always returns false.
92 * @return always false
93 */
94 final public boolean isDebugEnabled() {
95 return false;
96 }
97
98 /** A NOP implementation. */
99 final public void debug(String msg) {
100 // NOP
101 }
102
103 /** A NOP implementation. */
104 final public void debug(String format, Object arg) {
105 // NOP
106 }
107
108 /** A NOP implementation. */
109 public final void debug(String format, Object arg1, Object arg2) {
110 // NOP
111 }
112
113 /** A NOP implementation. */
114 public final void debug(String format, Object... argArray) {
115 // NOP
116 }
117
118 /** A NOP implementation. */
119 final public void debug(String msg, Throwable t) {
120 // NOP
121 }
122
123 /**
124 * Always returns false.
125 * @return always false
126 */
127 final public boolean isInfoEnabled() {
128 // NOP
129 return false;
130 }
131
132 /** A NOP implementation. */
133 final public void info(String msg) {
134 // NOP
135 }
136
137 /** A NOP implementation. */
138 final public void info(String format, Object arg1) {
139 // NOP
140 }
141
142 /** A NOP implementation. */
143 final public void info(String format, Object arg1, Object arg2) {
144 // NOP
145 }
146
147 /** A NOP implementation. */
148 public final void info(String format, Object... argArray) {
149 // NOP
150 }
151
152 /** A NOP implementation. */
153 final public void info(String msg, Throwable t) {
154 // NOP
155 }
156
157 /**
158 * Always returns false.
159 * @return always false
160 */
161 final public boolean isWarnEnabled() {
162 return false;
163 }
164
165 /** A NOP implementation. */
166 final public void warn(String msg) {
167 // NOP
168 }
169
170 /** A NOP implementation. */
171 final public void warn(String format, Object arg1) {
172 // NOP
173 }
174
175 /** A NOP implementation. */
176 final public void warn(String format, Object arg1, Object arg2) {
177 // NOP
178 }
179
180 /** A NOP implementation. */
181 public final void warn(String format, Object... argArray) {
182 // NOP
183 }
184
185 /** A NOP implementation. */
186 final public void warn(String msg, Throwable t) {
187 // NOP
188 }
189
190 /** A NOP implementation. */
191 final public boolean isErrorEnabled() {
192 return false;
193 }
194
195 /** A NOP implementation. */
196 final public void error(String msg) {
197 // NOP
198 }
199
200 /** A NOP implementation. */
201 final public void error(String format, Object arg1) {
202 // NOP
203 }
204
205 /** A NOP implementation. */
206 final public void error(String format, Object arg1, Object arg2) {
207 // NOP
208 }
209
210 /** A NOP implementation. */
211 public final void error(String format, Object... argArray) {
212 // NOP
213 }
214
215 /** A NOP implementation. */
216 final public void error(String msg, Throwable t) {
217 // NOP
218 }
219 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.Logger;
27 import org.slf4j.helpers.MarkerIgnoringBase;
28
29 /**
30 * A direct NOP (no operation) implementation of {@link Logger}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class NOPLogger extends MarkerIgnoringBase {
35
36 private static final long serialVersionUID = -517220405410904473L;
37
38 /**
39 * The unique instance of NOPLogger.
40 */
41 public static final NOPLogger NOP_LOGGER = new NOPLogger();
42
43 /**
44 * There is no point in creating multiple instances of NOPLogger,
45 * except by derived classes, hence the protected access for the constructor.
46 */
47 protected NOPLogger() {
48 }
49
50 /**
51 * Always returns the string value "NOP".
52 */
53 public String getName() {
54 return "NOP";
55 }
56
57 /**
58 * Always returns false.
59 * @return always false
60 */
61 final public boolean isTraceEnabled() {
62 return false;
63 }
64
65 /** A NOP implementation. */
66 final public void trace(String msg) {
67 // NOP
68 }
69
70 /** A NOP implementation. */
71 final public void trace(String format, Object arg) {
72 // NOP
73 }
74
75 /** A NOP implementation. */
76 public final void trace(String format, Object arg1, Object arg2) {
77 // NOP
78 }
79
80 /** A NOP implementation. */
81 public final void trace(String format, Object... argArray) {
82 // NOP
83 }
84
85 /** A NOP implementation. */
86 final public void trace(String msg, Throwable t) {
87 // NOP
88 }
89
90 /**
91 * Always returns false.
92 * @return always false
93 */
94 final public boolean isDebugEnabled() {
95 return false;
96 }
97
98 /** A NOP implementation. */
99 final public void debug(String msg) {
100 // NOP
101 }
102
103 /** A NOP implementation. */
104 final public void debug(String format, Object arg) {
105 // NOP
106 }
107
108 /** A NOP implementation. */
109 public final void debug(String format, Object arg1, Object arg2) {
110 // NOP
111 }
112
113 /** A NOP implementation. */
114 public final void debug(String format, Object... argArray) {
115 // NOP
116 }
117
118 /** A NOP implementation. */
119 final public void debug(String msg, Throwable t) {
120 // NOP
121 }
122
123 /**
124 * Always returns false.
125 * @return always false
126 */
127 final public boolean isInfoEnabled() {
128 // NOP
129 return false;
130 }
131
132 /** A NOP implementation. */
133 final public void info(String msg) {
134 // NOP
135 }
136
137 /** A NOP implementation. */
138 final public void info(String format, Object arg1) {
139 // NOP
140 }
141
142 /** A NOP implementation. */
143 final public void info(String format, Object arg1, Object arg2) {
144 // NOP
145 }
146
147 /** A NOP implementation. */
148 public final void info(String format, Object... argArray) {
149 // NOP
150 }
151
152 /** A NOP implementation. */
153 final public void info(String msg, Throwable t) {
154 // NOP
155 }
156
157 /**
158 * Always returns false.
159 * @return always false
160 */
161 final public boolean isWarnEnabled() {
162 return false;
163 }
164
165 /** A NOP implementation. */
166 final public void warn(String msg) {
167 // NOP
168 }
169
170 /** A NOP implementation. */
171 final public void warn(String format, Object arg1) {
172 // NOP
173 }
174
175 /** A NOP implementation. */
176 final public void warn(String format, Object arg1, Object arg2) {
177 // NOP
178 }
179
180 /** A NOP implementation. */
181 public final void warn(String format, Object... argArray) {
182 // NOP
183 }
184
185 /** A NOP implementation. */
186 final public void warn(String msg, Throwable t) {
187 // NOP
188 }
189
190 /** A NOP implementation. */
191 final public boolean isErrorEnabled() {
192 return false;
193 }
194
195 /** A NOP implementation. */
196 final public void error(String msg) {
197 // NOP
198 }
199
200 /** A NOP implementation. */
201 final public void error(String format, Object arg1) {
202 // NOP
203 }
204
205 /** A NOP implementation. */
206 final public void error(String format, Object arg1, Object arg2) {
207 // NOP
208 }
209
210 /** A NOP implementation. */
211 public final void error(String format, Object... argArray) {
212 // NOP
213 }
214
215 /** A NOP implementation. */
216 final public void error(String msg, Throwable t) {
217 // NOP
218 }
219 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.Logger;
28 import org.slf4j.helpers.NOPLogger;
29
30 /**
31 * NOPLoggerFactory is an trivial implementation of {@link
32 * ILoggerFactory} which always returns the unique instance of
33 * NOPLogger.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public class NOPLoggerFactory implements ILoggerFactory {
38
39 public NOPLoggerFactory() {
40 // nothing to do
41 }
42
43 public Logger getLogger(String name) {
44 return NOPLogger.NOP_LOGGER;
45 }
46
47 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.Logger;
28 import org.slf4j.helpers.NOPLogger;
29
30 /**
31 * NOPLoggerFactory is an trivial implementation of {@link
32 * ILoggerFactory} which always returns the unique instance of
33 * NOPLogger.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public class NOPLoggerFactory implements ILoggerFactory {
38
39 public NOPLoggerFactory() {
40 // nothing to do
41 }
42
43 public Logger getLogger(String name) {
44 return NOPLogger.NOP_LOGGER;
45 }
46
47 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.Map;
27
28 import org.slf4j.spi.MDCAdapter;
29
30 /**
31 * This adapter is an empty implementation of the {@link MDCAdapter} interface.
32 * It is used for all logging systems which do not support mapped
33 * diagnostic contexts such as JDK14, simple and NOP.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 *
37 * @since 1.4.1
38 */
39 public class NOPMDCAdapter implements MDCAdapter {
40
41 public void clear() {
42 }
43
44 public String get(String key) {
45 return null;
46 }
47
48 public void put(String key, String val) {
49 }
50
51 public void remove(String key) {
52 }
53
54 public Map<String, String> getCopyOfContextMap() {
55 return null;
56 }
57
58 public void setContextMap(Map<String, String> contextMap) {
59 // NOP
60 }
61
62 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.Map;
27
28 import org.slf4j.spi.MDCAdapter;
29
30 /**
31 * This adapter is an empty implementation of the {@link MDCAdapter} interface.
32 * It is used for all logging systems which do not support mapped
33 * diagnostic contexts such as JDK14, simple and NOP.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 *
37 * @since 1.4.1
38 */
39 public class NOPMDCAdapter implements MDCAdapter {
40
41 public void clear() {
42 }
43
44 public String get(String key) {
45 return null;
46 }
47
48 public void put(String key, String val) {
49 }
50
51 public void remove(String key) {
52 }
53
54 public Map<String, String> getCopyOfContextMap() {
55 return null;
56 }
57
58 public void setContextMap(Map<String, String> contextMap) {
59 // NOP
60 }
61
62 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.io.ObjectStreamException;
27 import java.io.Serializable;
28
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33 * Serves as base class for named logger implementation. More significantly, this
34 * class establishes deserialization behavior.
35 *
36 * @author Ceki Gulcu
37 * @see #readResolve
38 * @since 1.5.3
39 */
40 abstract class NamedLoggerBase implements Logger, Serializable {
41
42 private static final long serialVersionUID = 7535258609338176893L;
43
44 protected String name;
45
46 public String getName() {
47 return name;
48 }
49
50 /**
51 * Replace this instance with a homonymous (same name) logger returned
52 * by LoggerFactory. Note that this method is only called during
53 * deserialization.
54 *
55 * <p>
56 * This approach will work well if the desired ILoggerFactory is the one
57 * references by LoggerFactory. However, if the user manages its logger hierarchy
58 * through a different (non-static) mechanism, e.g. dependency injection, then
59 * this approach would be mostly counterproductive.
60 *
61 * @return logger with same name as returned by LoggerFactory
62 * @throws ObjectStreamException
63 */
64 protected Object readResolve() throws ObjectStreamException {
65 // using getName() instead of this.name works even for
66 // NOPLogger
67 return LoggerFactory.getLogger(getName());
68 }
69
70 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.io.ObjectStreamException;
27 import java.io.Serializable;
28
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33 * Serves as base class for named logger implementation. More significantly, this
34 * class establishes deserialization behavior.
35 *
36 * @author Ceki Gulcu
37 * @see #readResolve
38 * @since 1.5.3
39 */
40 abstract class NamedLoggerBase implements Logger, Serializable {
41
42 private static final long serialVersionUID = 7535258609338176893L;
43
44 protected String name;
45
46 public String getName() {
47 return name;
48 }
49
50 /**
51 * Replace this instance with a homonymous (same name) logger returned
52 * by LoggerFactory. Note that this method is only called during
53 * deserialization.
54 *
55 * <p>
56 * This approach will work well if the desired ILoggerFactory is the one
57 * references by LoggerFactory. However, if the user manages its logger hierarchy
58 * through a different (non-static) mechanism, e.g. dependency injection, then
59 * this approach would be mostly counterproductive.
60 *
61 * @return logger with same name as returned by LoggerFactory
62 * @throws ObjectStreamException
63 */
64 protected Object readResolve() throws ObjectStreamException {
65 // using getName() instead of this.name works even for
66 // NOPLogger
67 return LoggerFactory.getLogger(getName());
68 }
69
70 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.lang.reflect.InvocationTargetException;
27 import java.lang.reflect.Method;
28 import java.util.Queue;
29
30 import org.slf4j.Logger;
31 import org.slf4j.Marker;
32 import org.slf4j.event.EventRecodingLogger;
33 import org.slf4j.event.LoggingEvent;
34 import org.slf4j.event.SubstituteLoggingEvent;
35
36 /**
37 * A logger implementation which logs via a delegate logger. By default, the delegate is a
38 * {@link NOPLogger}. However, a different delegate can be set at any time.
39 * <p/>
40 * See also the <a href="http://www.slf4j.org/codes.html#substituteLogger">relevant
41 * error code</a> documentation.
42 *
43 * @author Chetan Mehrotra
44 * @author Ceki Gulcu
45 */
46 public class SubstituteLogger implements Logger {
47
48 private final String name;
49 private volatile Logger _delegate;
50 private Boolean delegateEventAware;
51 private Method logMethodCache;
52 private EventRecodingLogger eventRecodingLogger;
53 private Queue<SubstituteLoggingEvent> eventQueue;
54
55 private final boolean createdPostInitialization;
56
57 public SubstituteLogger(String name, Queue<SubstituteLoggingEvent> eventQueue, boolean createdPostInitialization) {
58 this.name = name;
59 this.eventQueue = eventQueue;
60 this.createdPostInitialization = createdPostInitialization;
61 }
62
63 public String getName() {
64 return name;
65 }
66
67 public boolean isTraceEnabled() {
68 return delegate().isTraceEnabled();
69 }
70
71 public void trace(String msg) {
72 delegate().trace(msg);
73 }
74
75 public void trace(String format, Object arg) {
76 delegate().trace(format, arg);
77 }
78
79 public void trace(String format, Object arg1, Object arg2) {
80 delegate().trace(format, arg1, arg2);
81 }
82
83 public void trace(String format, Object... arguments) {
84 delegate().trace(format, arguments);
85 }
86
87 public void trace(String msg, Throwable t) {
88 delegate().trace(msg, t);
89 }
90
91 public boolean isTraceEnabled(Marker marker) {
92 return delegate().isTraceEnabled(marker);
93 }
94
95 public void trace(Marker marker, String msg) {
96 delegate().trace(marker, msg);
97 }
98
99 public void trace(Marker marker, String format, Object arg) {
100 delegate().trace(marker, format, arg);
101 }
102
103 public void trace(Marker marker, String format, Object arg1, Object arg2) {
104 delegate().trace(marker, format, arg1, arg2);
105 }
106
107 public void trace(Marker marker, String format, Object... arguments) {
108 delegate().trace(marker, format, arguments);
109 }
110
111 public void trace(Marker marker, String msg, Throwable t) {
112 delegate().trace(marker, msg, t);
113 }
114
115 public boolean isDebugEnabled() {
116 return delegate().isDebugEnabled();
117 }
118
119 public void debug(String msg) {
120 delegate().debug(msg);
121 }
122
123 public void debug(String format, Object arg) {
124 delegate().debug(format, arg);
125 }
126
127 public void debug(String format, Object arg1, Object arg2) {
128 delegate().debug(format, arg1, arg2);
129 }
130
131 public void debug(String format, Object... arguments) {
132 delegate().debug(format, arguments);
133 }
134
135 public void debug(String msg, Throwable t) {
136 delegate().debug(msg, t);
137 }
138
139 public boolean isDebugEnabled(Marker marker) {
140 return delegate().isDebugEnabled(marker);
141 }
142
143 public void debug(Marker marker, String msg) {
144 delegate().debug(marker, msg);
145 }
146
147 public void debug(Marker marker, String format, Object arg) {
148 delegate().debug(marker, format, arg);
149 }
150
151 public void debug(Marker marker, String format, Object arg1, Object arg2) {
152 delegate().debug(marker, format, arg1, arg2);
153 }
154
155 public void debug(Marker marker, String format, Object... arguments) {
156 delegate().debug(marker, format, arguments);
157 }
158
159 public void debug(Marker marker, String msg, Throwable t) {
160 delegate().debug(marker, msg, t);
161 }
162
163 public boolean isInfoEnabled() {
164 return delegate().isInfoEnabled();
165 }
166
167 public void info(String msg) {
168 delegate().info(msg);
169 }
170
171 public void info(String format, Object arg) {
172 delegate().info(format, arg);
173 }
174
175 public void info(String format, Object arg1, Object arg2) {
176 delegate().info(format, arg1, arg2);
177 }
178
179 public void info(String format, Object... arguments) {
180 delegate().info(format, arguments);
181 }
182
183 public void info(String msg, Throwable t) {
184 delegate().info(msg, t);
185 }
186
187 public boolean isInfoEnabled(Marker marker) {
188 return delegate().isInfoEnabled(marker);
189 }
190
191 public void info(Marker marker, String msg) {
192 delegate().info(marker, msg);
193 }
194
195 public void info(Marker marker, String format, Object arg) {
196 delegate().info(marker, format, arg);
197 }
198
199 public void info(Marker marker, String format, Object arg1, Object arg2) {
200 delegate().info(marker, format, arg1, arg2);
201 }
202
203 public void info(Marker marker, String format, Object... arguments) {
204 delegate().info(marker, format, arguments);
205 }
206
207 public void info(Marker marker, String msg, Throwable t) {
208 delegate().info(marker, msg, t);
209 }
210
211 public boolean isWarnEnabled() {
212 return delegate().isWarnEnabled();
213 }
214
215 public void warn(String msg) {
216 delegate().warn(msg);
217 }
218
219 public void warn(String format, Object arg) {
220 delegate().warn(format, arg);
221 }
222
223 public void warn(String format, Object arg1, Object arg2) {
224 delegate().warn(format, arg1, arg2);
225 }
226
227 public void warn(String format, Object... arguments) {
228 delegate().warn(format, arguments);
229 }
230
231 public void warn(String msg, Throwable t) {
232 delegate().warn(msg, t);
233 }
234
235 public boolean isWarnEnabled(Marker marker) {
236 return delegate().isWarnEnabled(marker);
237 }
238
239 public void warn(Marker marker, String msg) {
240 delegate().warn(marker, msg);
241 }
242
243 public void warn(Marker marker, String format, Object arg) {
244 delegate().warn(marker, format, arg);
245 }
246
247 public void warn(Marker marker, String format, Object arg1, Object arg2) {
248 delegate().warn(marker, format, arg1, arg2);
249 }
250
251 public void warn(Marker marker, String format, Object... arguments) {
252 delegate().warn(marker, format, arguments);
253 }
254
255 public void warn(Marker marker, String msg, Throwable t) {
256 delegate().warn(marker, msg, t);
257 }
258
259 public boolean isErrorEnabled() {
260 return delegate().isErrorEnabled();
261 }
262
263 public void error(String msg) {
264 delegate().error(msg);
265 }
266
267 public void error(String format, Object arg) {
268 delegate().error(format, arg);
269 }
270
271 public void error(String format, Object arg1, Object arg2) {
272 delegate().error(format, arg1, arg2);
273 }
274
275 public void error(String format, Object... arguments) {
276 delegate().error(format, arguments);
277 }
278
279 public void error(String msg, Throwable t) {
280 delegate().error(msg, t);
281 }
282
283 public boolean isErrorEnabled(Marker marker) {
284 return delegate().isErrorEnabled(marker);
285 }
286
287 public void error(Marker marker, String msg) {
288 delegate().error(marker, msg);
289 }
290
291 public void error(Marker marker, String format, Object arg) {
292 delegate().error(marker, format, arg);
293 }
294
295 public void error(Marker marker, String format, Object arg1, Object arg2) {
296 delegate().error(marker, format, arg1, arg2);
297 }
298
299 public void error(Marker marker, String format, Object... arguments) {
300 delegate().error(marker, format, arguments);
301 }
302
303 public void error(Marker marker, String msg, Throwable t) {
304 delegate().error(marker, msg, t);
305 }
306
307 @Override
308 public boolean equals(Object o) {
309 if (this == o)
310 return true;
311 if (o == null || getClass() != o.getClass())
312 return false;
313
314 SubstituteLogger that = (SubstituteLogger) o;
315
316 if (!name.equals(that.name))
317 return false;
318
319 return true;
320 }
321
322 @Override
323 public int hashCode() {
324 return name.hashCode();
325 }
326
327 /**
328 * Return the delegate logger instance if set. Otherwise, return a {@link NOPLogger}
329 * instance.
330 */
331 Logger delegate() {
332 if(_delegate != null) {
333 return _delegate;
334 }
335 if(createdPostInitialization) {
336 return NOPLogger.NOP_LOGGER;
337 } else {
338 return getEventRecordingLogger();
339 }
340 }
341
342 private Logger getEventRecordingLogger() {
343 if (eventRecodingLogger == null) {
344 eventRecodingLogger = new EventRecodingLogger(this, eventQueue);
345 }
346 return eventRecodingLogger;
347 }
348
349 /**
350 * Typically called after the {@link org.slf4j.LoggerFactory} initialization phase is completed.
351 * @param delegate
352 */
353 public void setDelegate(Logger delegate) {
354 this._delegate = delegate;
355 }
356
357 public boolean isDelegateEventAware() {
358 if (delegateEventAware != null)
359 return delegateEventAware;
360
361 try {
362 logMethodCache = _delegate.getClass().getMethod("log", LoggingEvent.class);
363 delegateEventAware = Boolean.TRUE;
364 } catch (NoSuchMethodException e) {
365 delegateEventAware = Boolean.FALSE;
366 }
367 return delegateEventAware;
368 }
369
370 public void log(LoggingEvent event) {
371 if (isDelegateEventAware()) {
372 try {
373 logMethodCache.invoke(_delegate, event);
374 } catch (IllegalAccessException e) {
375 } catch (IllegalArgumentException e) {
376 } catch (InvocationTargetException e) {
377 }
378 }
379 }
380
381
382 public boolean isDelegateNull() {
383 return _delegate == null;
384 }
385
386 public boolean isDelegateNOP() {
387 return _delegate instanceof NOPLogger;
388 }
389 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.lang.reflect.InvocationTargetException;
27 import java.lang.reflect.Method;
28 import java.util.Queue;
29
30 import org.slf4j.Logger;
31 import org.slf4j.Marker;
32 import org.slf4j.event.EventRecodingLogger;
33 import org.slf4j.event.LoggingEvent;
34 import org.slf4j.event.SubstituteLoggingEvent;
35
36 /**
37 * A logger implementation which logs via a delegate logger. By default, the delegate is a
38 * {@link NOPLogger}. However, a different delegate can be set at any time.
39 * <p/>
40 * See also the <a href="http://www.slf4j.org/codes.html#substituteLogger">relevant
41 * error code</a> documentation.
42 *
43 * @author Chetan Mehrotra
44 * @author Ceki Gulcu
45 */
46 public class SubstituteLogger implements Logger {
47
48 private final String name;
49 private volatile Logger _delegate;
50 private Boolean delegateEventAware;
51 private Method logMethodCache;
52 private EventRecodingLogger eventRecodingLogger;
53 private Queue<SubstituteLoggingEvent> eventQueue;
54
55 private final boolean createdPostInitialization;
56
57 public SubstituteLogger(String name, Queue<SubstituteLoggingEvent> eventQueue, boolean createdPostInitialization) {
58 this.name = name;
59 this.eventQueue = eventQueue;
60 this.createdPostInitialization = createdPostInitialization;
61 }
62
63 public String getName() {
64 return name;
65 }
66
67 public boolean isTraceEnabled() {
68 return delegate().isTraceEnabled();
69 }
70
71 public void trace(String msg) {
72 delegate().trace(msg);
73 }
74
75 public void trace(String format, Object arg) {
76 delegate().trace(format, arg);
77 }
78
79 public void trace(String format, Object arg1, Object arg2) {
80 delegate().trace(format, arg1, arg2);
81 }
82
83 public void trace(String format, Object... arguments) {
84 delegate().trace(format, arguments);
85 }
86
87 public void trace(String msg, Throwable t) {
88 delegate().trace(msg, t);
89 }
90
91 public boolean isTraceEnabled(Marker marker) {
92 return delegate().isTraceEnabled(marker);
93 }
94
95 public void trace(Marker marker, String msg) {
96 delegate().trace(marker, msg);
97 }
98
99 public void trace(Marker marker, String format, Object arg) {
100 delegate().trace(marker, format, arg);
101 }
102
103 public void trace(Marker marker, String format, Object arg1, Object arg2) {
104 delegate().trace(marker, format, arg1, arg2);
105 }
106
107 public void trace(Marker marker, String format, Object... arguments) {
108 delegate().trace(marker, format, arguments);
109 }
110
111 public void trace(Marker marker, String msg, Throwable t) {
112 delegate().trace(marker, msg, t);
113 }
114
115 public boolean isDebugEnabled() {
116 return delegate().isDebugEnabled();
117 }
118
119 public void debug(String msg) {
120 delegate().debug(msg);
121 }
122
123 public void debug(String format, Object arg) {
124 delegate().debug(format, arg);
125 }
126
127 public void debug(String format, Object arg1, Object arg2) {
128 delegate().debug(format, arg1, arg2);
129 }
130
131 public void debug(String format, Object... arguments) {
132 delegate().debug(format, arguments);
133 }
134
135 public void debug(String msg, Throwable t) {
136 delegate().debug(msg, t);
137 }
138
139 public boolean isDebugEnabled(Marker marker) {
140 return delegate().isDebugEnabled(marker);
141 }
142
143 public void debug(Marker marker, String msg) {
144 delegate().debug(marker, msg);
145 }
146
147 public void debug(Marker marker, String format, Object arg) {
148 delegate().debug(marker, format, arg);
149 }
150
151 public void debug(Marker marker, String format, Object arg1, Object arg2) {
152 delegate().debug(marker, format, arg1, arg2);
153 }
154
155 public void debug(Marker marker, String format, Object... arguments) {
156 delegate().debug(marker, format, arguments);
157 }
158
159 public void debug(Marker marker, String msg, Throwable t) {
160 delegate().debug(marker, msg, t);
161 }
162
163 public boolean isInfoEnabled() {
164 return delegate().isInfoEnabled();
165 }
166
167 public void info(String msg) {
168 delegate().info(msg);
169 }
170
171 public void info(String format, Object arg) {
172 delegate().info(format, arg);
173 }
174
175 public void info(String format, Object arg1, Object arg2) {
176 delegate().info(format, arg1, arg2);
177 }
178
179 public void info(String format, Object... arguments) {
180 delegate().info(format, arguments);
181 }
182
183 public void info(String msg, Throwable t) {
184 delegate().info(msg, t);
185 }
186
187 public boolean isInfoEnabled(Marker marker) {
188 return delegate().isInfoEnabled(marker);
189 }
190
191 public void info(Marker marker, String msg) {
192 delegate().info(marker, msg);
193 }
194
195 public void info(Marker marker, String format, Object arg) {
196 delegate().info(marker, format, arg);
197 }
198
199 public void info(Marker marker, String format, Object arg1, Object arg2) {
200 delegate().info(marker, format, arg1, arg2);
201 }
202
203 public void info(Marker marker, String format, Object... arguments) {
204 delegate().info(marker, format, arguments);
205 }
206
207 public void info(Marker marker, String msg, Throwable t) {
208 delegate().info(marker, msg, t);
209 }
210
211 public boolean isWarnEnabled() {
212 return delegate().isWarnEnabled();
213 }
214
215 public void warn(String msg) {
216 delegate().warn(msg);
217 }
218
219 public void warn(String format, Object arg) {
220 delegate().warn(format, arg);
221 }
222
223 public void warn(String format, Object arg1, Object arg2) {
224 delegate().warn(format, arg1, arg2);
225 }
226
227 public void warn(String format, Object... arguments) {
228 delegate().warn(format, arguments);
229 }
230
231 public void warn(String msg, Throwable t) {
232 delegate().warn(msg, t);
233 }
234
235 public boolean isWarnEnabled(Marker marker) {
236 return delegate().isWarnEnabled(marker);
237 }
238
239 public void warn(Marker marker, String msg) {
240 delegate().warn(marker, msg);
241 }
242
243 public void warn(Marker marker, String format, Object arg) {
244 delegate().warn(marker, format, arg);
245 }
246
247 public void warn(Marker marker, String format, Object arg1, Object arg2) {
248 delegate().warn(marker, format, arg1, arg2);
249 }
250
251 public void warn(Marker marker, String format, Object... arguments) {
252 delegate().warn(marker, format, arguments);
253 }
254
255 public void warn(Marker marker, String msg, Throwable t) {
256 delegate().warn(marker, msg, t);
257 }
258
259 public boolean isErrorEnabled() {
260 return delegate().isErrorEnabled();
261 }
262
263 public void error(String msg) {
264 delegate().error(msg);
265 }
266
267 public void error(String format, Object arg) {
268 delegate().error(format, arg);
269 }
270
271 public void error(String format, Object arg1, Object arg2) {
272 delegate().error(format, arg1, arg2);
273 }
274
275 public void error(String format, Object... arguments) {
276 delegate().error(format, arguments);
277 }
278
279 public void error(String msg, Throwable t) {
280 delegate().error(msg, t);
281 }
282
283 public boolean isErrorEnabled(Marker marker) {
284 return delegate().isErrorEnabled(marker);
285 }
286
287 public void error(Marker marker, String msg) {
288 delegate().error(marker, msg);
289 }
290
291 public void error(Marker marker, String format, Object arg) {
292 delegate().error(marker, format, arg);
293 }
294
295 public void error(Marker marker, String format, Object arg1, Object arg2) {
296 delegate().error(marker, format, arg1, arg2);
297 }
298
299 public void error(Marker marker, String format, Object... arguments) {
300 delegate().error(marker, format, arguments);
301 }
302
303 public void error(Marker marker, String msg, Throwable t) {
304 delegate().error(marker, msg, t);
305 }
306
307 @Override
308 public boolean equals(Object o) {
309 if (this == o)
310 return true;
311 if (o == null || getClass() != o.getClass())
312 return false;
313
314 SubstituteLogger that = (SubstituteLogger) o;
315
316 if (!name.equals(that.name))
317 return false;
318
319 return true;
320 }
321
322 @Override
323 public int hashCode() {
324 return name.hashCode();
325 }
326
327 /**
328 * Return the delegate logger instance if set. Otherwise, return a {@link NOPLogger}
329 * instance.
330 */
331 Logger delegate() {
332 if(_delegate != null) {
333 return _delegate;
334 }
335 if(createdPostInitialization) {
336 return NOPLogger.NOP_LOGGER;
337 } else {
338 return getEventRecordingLogger();
339 }
340 }
341
342 private Logger getEventRecordingLogger() {
343 if (eventRecodingLogger == null) {
344 eventRecodingLogger = new EventRecodingLogger(this, eventQueue);
345 }
346 return eventRecodingLogger;
347 }
348
349 /**
350 * Typically called after the {@link org.slf4j.LoggerFactory} initialization phase is completed.
351 * @param delegate
352 */
353 public void setDelegate(Logger delegate) {
354 this._delegate = delegate;
355 }
356
357 public boolean isDelegateEventAware() {
358 if (delegateEventAware != null)
359 return delegateEventAware;
360
361 try {
362 logMethodCache = _delegate.getClass().getMethod("log", LoggingEvent.class);
363 delegateEventAware = Boolean.TRUE;
364 } catch (NoSuchMethodException e) {
365 delegateEventAware = Boolean.FALSE;
366 }
367 return delegateEventAware;
368 }
369
370 public void log(LoggingEvent event) {
371 if (isDelegateEventAware()) {
372 try {
373 logMethodCache.invoke(_delegate, event);
374 } catch (IllegalAccessException e) {
375 } catch (IllegalArgumentException e) {
376 } catch (InvocationTargetException e) {
377 }
378 }
379 }
380
381
382 public boolean isDelegateNull() {
383 return _delegate == null;
384 }
385
386 public boolean isDelegateNOP() {
387 return _delegate instanceof NOPLogger;
388 }
389 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.concurrent.LinkedBlockingQueue;
31
32 import org.slf4j.ILoggerFactory;
33 import org.slf4j.Logger;
34 import org.slf4j.event.SubstituteLoggingEvent;
35
36 /**
37 * SubstituteLoggerFactory manages instances of {@link SubstituteLogger}.
38 *
39 * @author Ceki G&uuml;lc&uuml;
40 * @author Chetan Mehrotra
41 */
42 public class SubstituteLoggerFactory implements ILoggerFactory {
43
44 boolean postInitialization = false;
45
46 final Map<String, SubstituteLogger> loggers = new HashMap<String, SubstituteLogger>();
47
48 final LinkedBlockingQueue<SubstituteLoggingEvent> eventQueue = new LinkedBlockingQueue<SubstituteLoggingEvent>();
49
50 synchronized public Logger getLogger(String name) {
51 SubstituteLogger logger = loggers.get(name);
52 if (logger == null) {
53 logger = new SubstituteLogger(name, eventQueue, postInitialization);
54 loggers.put(name, logger);
55 }
56 return logger;
57 }
58
59 public List<String> getLoggerNames() {
60 return new ArrayList<String>(loggers.keySet());
61 }
62
63 public List<SubstituteLogger> getLoggers() {
64 return new ArrayList<SubstituteLogger>(loggers.values());
65 }
66
67 public LinkedBlockingQueue<SubstituteLoggingEvent> getEventQueue() {
68 return eventQueue;
69 }
70
71 public void postInitialization() {
72 postInitialization = true;
73 }
74
75 public void clear() {
76 loggers.clear();
77 eventQueue.clear();
78 }
79 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.concurrent.LinkedBlockingQueue;
31
32 import org.slf4j.ILoggerFactory;
33 import org.slf4j.Logger;
34 import org.slf4j.event.SubstituteLoggingEvent;
35
36 /**
37 * SubstituteLoggerFactory manages instances of {@link SubstituteLogger}.
38 *
39 * @author Ceki G&uuml;lc&uuml;
40 * @author Chetan Mehrotra
41 */
42 public class SubstituteLoggerFactory implements ILoggerFactory {
43
44 boolean postInitialization = false;
45
46 final Map<String, SubstituteLogger> loggers = new HashMap<String, SubstituteLogger>();
47
48 final LinkedBlockingQueue<SubstituteLoggingEvent> eventQueue = new LinkedBlockingQueue<SubstituteLoggingEvent>();
49
50 synchronized public Logger getLogger(String name) {
51 SubstituteLogger logger = loggers.get(name);
52 if (logger == null) {
53 logger = new SubstituteLogger(name, eventQueue, postInitialization);
54 loggers.put(name, logger);
55 }
56 return logger;
57 }
58
59 public List<String> getLoggerNames() {
60 return new ArrayList<String>(loggers.keySet());
61 }
62
63 public List<SubstituteLogger> getLoggers() {
64 return new ArrayList<SubstituteLogger>(loggers.values());
65 }
66
67 public LinkedBlockingQueue<SubstituteLoggingEvent> getEventQueue() {
68 return eventQueue;
69 }
70
71 public void postInitialization() {
72 postInitialization = true;
73 }
74
75 public void clear() {
76 loggers.clear();
77 eventQueue.clear();
78 }
79 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 /**
27 * An internal utility class.
28 *
29 * @author Alexander Dorokhine
30 * @author Ceki G&uuml;lc&uuml;
31 */
32 public final class Util {
33
34
35 private Util() {
36 }
37
38 public static String safeGetSystemProperty(String key) {
39 if (key == null)
40 throw new IllegalArgumentException("null input");
41
42 String result = null;
43 try {
44 result = System.getProperty(key);
45 } catch (java.lang.SecurityException sm) {
46 ; // ignore
47 }
48 return result;
49 }
50
51 public static boolean safeGetBooleanSystemProperty(String key) {
52 String value = safeGetSystemProperty(key);
53 if (value == null)
54 return false;
55 else
56 return value.equalsIgnoreCase("true");
57 }
58
59 /**
60 * In order to call {@link SecurityManager#getClassContext()}, which is a
61 * protected method, we add this wrapper which allows the method to be visible
62 * inside this package.
63 */
64 private static final class ClassContextSecurityManager extends SecurityManager {
65 protected Class<?>[] getClassContext() {
66 return super.getClassContext();
67 }
68 }
69
70 private static ClassContextSecurityManager SECURITY_MANAGER;
71 private static boolean SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED = false;
72
73 private static ClassContextSecurityManager getSecurityManager() {
74 if (SECURITY_MANAGER != null)
75 return SECURITY_MANAGER;
76 else if (SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED)
77 return null;
78 else {
79 SECURITY_MANAGER = safeCreateSecurityManager();
80 SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED = true;
81 return SECURITY_MANAGER;
82 }
83 }
84
85 private static ClassContextSecurityManager safeCreateSecurityManager() {
86 try {
87 return new ClassContextSecurityManager();
88 } catch (java.lang.SecurityException sm) {
89 return null;
90 }
91 }
92
93 /**
94 * Returns the name of the class which called the invoking method.
95 *
96 * @return the name of the class which called the invoking method.
97 */
98 public static Class<?> getCallingClass() {
99 ClassContextSecurityManager securityManager = getSecurityManager();
100 if (securityManager == null)
101 return null;
102 Class<?>[] trace = securityManager.getClassContext();
103 String thisClassName = Util.class.getName();
104
105 // Advance until Util is found
106 int i;
107 for (i = 0; i < trace.length; i++) {
108 if (thisClassName.equals(trace[i].getName()))
109 break;
110 }
111
112 // trace[i] = Util; trace[i+1] = caller; trace[i+2] = caller's caller
113 if (i >= trace.length || i + 2 >= trace.length) {
114 throw new IllegalStateException("Failed to find org.slf4j.helpers.Util or its caller in the stack; " + "this should not happen");
115 }
116
117 return trace[i + 2];
118 }
119
120 static final public void report(String msg, Throwable t) {
121 System.err.println(msg);
122 System.err.println("Reported exception:");
123 t.printStackTrace();
124 }
125
126 static final public void report(String msg) {
127 System.err.println("SLF4J: " + msg);
128 }
129
130
131
132 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 /**
27 * An internal utility class.
28 *
29 * @author Alexander Dorokhine
30 * @author Ceki G&uuml;lc&uuml;
31 */
32 public final class Util {
33
34
35 private Util() {
36 }
37
38 public static String safeGetSystemProperty(String key) {
39 if (key == null)
40 throw new IllegalArgumentException("null input");
41
42 String result = null;
43 try {
44 result = System.getProperty(key);
45 } catch (java.lang.SecurityException sm) {
46 ; // ignore
47 }
48 return result;
49 }
50
51 public static boolean safeGetBooleanSystemProperty(String key) {
52 String value = safeGetSystemProperty(key);
53 if (value == null)
54 return false;
55 else
56 return value.equalsIgnoreCase("true");
57 }
58
59 /**
60 * In order to call {@link SecurityManager#getClassContext()}, which is a
61 * protected method, we add this wrapper which allows the method to be visible
62 * inside this package.
63 */
64 private static final class ClassContextSecurityManager extends SecurityManager {
65 protected Class<?>[] getClassContext() {
66 return super.getClassContext();
67 }
68 }
69
70 private static ClassContextSecurityManager SECURITY_MANAGER;
71 private static boolean SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED = false;
72
73 private static ClassContextSecurityManager getSecurityManager() {
74 if (SECURITY_MANAGER != null)
75 return SECURITY_MANAGER;
76 else if (SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED)
77 return null;
78 else {
79 SECURITY_MANAGER = safeCreateSecurityManager();
80 SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED = true;
81 return SECURITY_MANAGER;
82 }
83 }
84
85 private static ClassContextSecurityManager safeCreateSecurityManager() {
86 try {
87 return new ClassContextSecurityManager();
88 } catch (java.lang.SecurityException sm) {
89 return null;
90 }
91 }
92
93 /**
94 * Returns the name of the class which called the invoking method.
95 *
96 * @return the name of the class which called the invoking method.
97 */
98 public static Class<?> getCallingClass() {
99 ClassContextSecurityManager securityManager = getSecurityManager();
100 if (securityManager == null)
101 return null;
102 Class<?>[] trace = securityManager.getClassContext();
103 String thisClassName = Util.class.getName();
104
105 // Advance until Util is found
106 int i;
107 for (i = 0; i < trace.length; i++) {
108 if (thisClassName.equals(trace[i].getName()))
109 break;
110 }
111
112 // trace[i] = Util; trace[i+1] = caller; trace[i+2] = caller's caller
113 if (i >= trace.length || i + 2 >= trace.length) {
114 throw new IllegalStateException("Failed to find org.slf4j.helpers.Util or its caller in the stack; " + "this should not happen");
115 }
116
117 return trace[i + 2];
118 }
119
120 static final public void report(String msg, Throwable t) {
121 System.err.println(msg);
122 System.err.println("Reported exception:");
123 t.printStackTrace();
124 }
125
126 static final public void report(String msg) {
127 System.err.println("SLF4J: " + msg);
128 }
129
130
131
132 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>Helper classes.</p>
12
13 <hr/>
14 </body>
15 </html>
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>Helper classes.</p>
12
13 <hr/>
14 </body>
15 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27
28 /**
29 * The binding of {@link org.slf4j.LoggerFactory} class with an actual instance of
30 * {@link ILoggerFactory} is performed using information returned by this class.
31 *
32 * This class is meant to provide a dummy StaticLoggerBinder to the slf4j-api module.
33 * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop,
34 * slf4j-log4j12 etc.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticLoggerBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticLoggerBinder singleton
49 */
50 public static final StaticLoggerBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Declare the version of the SLF4J API this implementation is compiled against.
56 * The value of this field is modified with each major release.
57 */
58 // to avoid constant folding by the compiler, this field must *not* be final
59 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
60
61 private StaticLoggerBinder() {
62 throw new UnsupportedOperationException("This code should have never made it into slf4j-api.jar");
63 }
64
65 public ILoggerFactory getLoggerFactory() {
66 throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar");
67 }
68
69 public String getLoggerFactoryClassStr() {
70 throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar");
71 }
72 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27
28 /**
29 * The binding of {@link org.slf4j.LoggerFactory} class with an actual instance of
30 * {@link ILoggerFactory} is performed using information returned by this class.
31 *
32 * This class is meant to provide a dummy StaticLoggerBinder to the slf4j-api module.
33 * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop,
34 * slf4j-log4j12 etc.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticLoggerBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticLoggerBinder singleton
49 */
50 public static final StaticLoggerBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Declare the version of the SLF4J API this implementation is compiled against.
56 * The value of this field is modified with each major release.
57 */
58 // to avoid constant folding by the compiler, this field must *not* be final
59 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
60
61 private StaticLoggerBinder() {
62 throw new UnsupportedOperationException("This code should have never made it into slf4j-api.jar");
63 }
64
65 public ILoggerFactory getLoggerFactory() {
66 throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar");
67 }
68
69 public String getLoggerFactoryClassStr() {
70 throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar");
71 }
72 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.spi.MDCAdapter;
27
28 /**
29 * This class is only a stub. Real implementations are found in
30 * each SLF4J binding project, e.g. slf4j-nop, slf4j-log4j12 etc.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 throw new UnsupportedOperationException("This code should never make it into the jar");
43 }
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticMDCBinder singleton
49 * @since 1.7.14
50 */
51 public static final StaticMDCBinder getSingleton() {
52 return SINGLETON;
53 }
54
55 /**
56 * Currently this method always returns an instance of
57 * {@link StaticMDCBinder}.
58 */
59 public MDCAdapter getMDCA() {
60 throw new UnsupportedOperationException("This code should never make it into the jar");
61 }
62
63 public String getMDCAdapterClassStr() {
64 throw new UnsupportedOperationException("This code should never make it into the jar");
65 }
66 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.spi.MDCAdapter;
27
28 /**
29 * This class is only a stub. Real implementations are found in
30 * each SLF4J binding project, e.g. slf4j-nop, slf4j-log4j12 etc.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 throw new UnsupportedOperationException("This code should never make it into the jar");
43 }
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticMDCBinder singleton
49 * @since 1.7.14
50 */
51 public static final StaticMDCBinder getSingleton() {
52 return SINGLETON;
53 }
54
55 /**
56 * Currently this method always returns an instance of
57 * {@link StaticMDCBinder}.
58 */
59 public MDCAdapter getMDCA() {
60 throw new UnsupportedOperationException("This code should never make it into the jar");
61 }
62
63 public String getMDCAdapterClassStr() {
64 throw new UnsupportedOperationException("This code should never make it into the jar");
65 }
66 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * This class is meant to provide a *dummy* StaticMarkerBinder to the slf4j-api module.
37 * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop,
38 * slf4j-simple, slf4j-log4j12 etc.
39 *
40 * @author Ceki G&uuml;lc&uuml;
41 */
42 public class StaticMarkerBinder implements MarkerFactoryBinder {
43
44 /**
45 * The unique instance of this class.
46 */
47 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
48
49 private StaticMarkerBinder() {
50 throw new UnsupportedOperationException("This code should never make it into the jar");
51 }
52
53 /**
54 * Return the singleton of this class.
55 *
56 * @return the StaticMarkerBinder singleton
57 * @since 1.7.14
58 */
59 public static StaticMarkerBinder getSingleton() {
60 return SINGLETON;
61 }
62
63 /**
64 * Currently this method always returns an instance of
65 * {@link BasicMarkerFactory}.
66 */
67 public IMarkerFactory getMarkerFactory() {
68 throw new UnsupportedOperationException("This code should never make it into the jar");
69 }
70
71 /**
72 * Currently, this method returns the class name of
73 * {@link BasicMarkerFactory}.
74 */
75 public String getMarkerFactoryClassStr() {
76 throw new UnsupportedOperationException("This code should never make it into the jar");
77 }
78
79 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * This class is meant to provide a *dummy* StaticMarkerBinder to the slf4j-api module.
37 * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop,
38 * slf4j-simple, slf4j-log4j12 etc.
39 *
40 * @author Ceki G&uuml;lc&uuml;
41 */
42 public class StaticMarkerBinder implements MarkerFactoryBinder {
43
44 /**
45 * The unique instance of this class.
46 */
47 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
48
49 private StaticMarkerBinder() {
50 throw new UnsupportedOperationException("This code should never make it into the jar");
51 }
52
53 /**
54 * Return the singleton of this class.
55 *
56 * @return the StaticMarkerBinder singleton
57 * @since 1.7.14
58 */
59 public static StaticMarkerBinder getSingleton() {
60 return SINGLETON;
61 }
62
63 /**
64 * Currently this method always returns an instance of
65 * {@link BasicMarkerFactory}.
66 */
67 public IMarkerFactory getMarkerFactory() {
68 throw new UnsupportedOperationException("This code should never make it into the jar");
69 }
70
71 /**
72 * Currently, this method returns the class name of
73 * {@link BasicMarkerFactory}.
74 */
75 public String getMarkerFactoryClassStr() {
76 throw new UnsupportedOperationException("This code should never make it into the jar");
77 }
78
79 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>Implementations of core logging interfaces defined in the {@link
12 org.slf4j} package.</p>
13
14 <hr/>
15 </body>
16 </html>
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>Implementations of core logging interfaces defined in the {@link
12 org.slf4j} package.</p>
13
14 <hr/>
15 </body>
16 </html>
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>Core logging interfaces.</p>
12
13 <hr/>
14 </body>
15 </html>
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>Core logging interfaces.</p>
12
13 <hr/>
14 </body>
15 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28
29 /**
30 * An <b>optional</b> interface helping integration with logging systems capable of
31 * extracting location information. This interface is mainly used by SLF4J bridges
32 * such as jcl-over-slf4j, jul-to-slf4j and log4j-over-slf4j or {@link Logger} wrappers
33 * which need to provide hints so that the underlying logging system can extract
34 * the correct location information (method name, line number).
35 *
36 * @author Ceki Gulcu
37 * @since 1.3
38 */
39 public interface LocationAwareLogger extends Logger {
40
41 // these constants should be in EventContants. However, in order to preserve binary backward compatibility
42 // we keep these constants here
43 final public int TRACE_INT = 00;
44 final public int DEBUG_INT = 10;
45 final public int INFO_INT = 20;
46 final public int WARN_INT = 30;
47 final public int ERROR_INT = 40;
48
49 /**
50 * Printing method with support for location information.
51 *
52 * @param marker The marker to be used for this event, may be null.
53 * @param fqcn The fully qualified class name of the <b>logger instance</b>,
54 * typically the logger class, logger bridge or a logger wrapper.
55 * @param level One of the level integers defined in this interface
56 * @param message The message for the log event
57 * @param t Throwable associated with the log event, may be null.
58 */
59 public void log(Marker marker, String fqcn, int level, String message, Object[] argArray, Throwable t);
60
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28
29 /**
30 * An <b>optional</b> interface helping integration with logging systems capable of
31 * extracting location information. This interface is mainly used by SLF4J bridges
32 * such as jcl-over-slf4j, jul-to-slf4j and log4j-over-slf4j or {@link Logger} wrappers
33 * which need to provide hints so that the underlying logging system can extract
34 * the correct location information (method name, line number).
35 *
36 * @author Ceki Gulcu
37 * @since 1.3
38 */
39 public interface LocationAwareLogger extends Logger {
40
41 // these constants should be in EventContants. However, in order to preserve binary backward compatibility
42 // we keep these constants here
43 final public int TRACE_INT = 00;
44 final public int DEBUG_INT = 10;
45 final public int INFO_INT = 20;
46 final public int WARN_INT = 30;
47 final public int ERROR_INT = 40;
48
49 /**
50 * Printing method with support for location information.
51 *
52 * @param marker The marker to be used for this event, may be null.
53 * @param fqcn The fully qualified class name of the <b>logger instance</b>,
54 * typically the logger class, logger bridge or a logger wrapper.
55 * @param level One of the level integers defined in this interface
56 * @param message The message for the log event
57 * @param t Throwable associated with the log event, may be null.
58 */
59 public void log(Marker marker, String fqcn, int level, String message, Object[] argArray, Throwable t);
60
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import org.slf4j.ILoggerFactory;
27
28 /**
29 * An internal interface which helps the static {@link org.slf4j.LoggerFactory}
30 * class bind with the appropriate {@link ILoggerFactory} instance.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public interface LoggerFactoryBinder {
35
36 /**
37 * Return the instance of {@link ILoggerFactory} that
38 * {@link org.slf4j.LoggerFactory} class should bind to.
39 *
40 * @return the instance of {@link ILoggerFactory} that
41 * {@link org.slf4j.LoggerFactory} class should bind to.
42 */
43 public ILoggerFactory getLoggerFactory();
44
45 /**
46 * The String form of the {@link ILoggerFactory} object that this
47 * <code>LoggerFactoryBinder</code> instance is <em>intended</em> to return.
48 *
49 * <p>This method allows the developer to interrogate this binder's intention
50 * which may be different from the {@link ILoggerFactory} instance it is able to
51 * yield in practice. The discrepancy should only occur in case of errors.
52 *
53 * @return the class name of the intended {@link ILoggerFactory} instance
54 */
55 public String getLoggerFactoryClassStr();
56 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import org.slf4j.ILoggerFactory;
27
28 /**
29 * An internal interface which helps the static {@link org.slf4j.LoggerFactory}
30 * class bind with the appropriate {@link ILoggerFactory} instance.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public interface LoggerFactoryBinder {
35
36 /**
37 * Return the instance of {@link ILoggerFactory} that
38 * {@link org.slf4j.LoggerFactory} class should bind to.
39 *
40 * @return the instance of {@link ILoggerFactory} that
41 * {@link org.slf4j.LoggerFactory} class should bind to.
42 */
43 public ILoggerFactory getLoggerFactory();
44
45 /**
46 * The String form of the {@link ILoggerFactory} object that this
47 * <code>LoggerFactoryBinder</code> instance is <em>intended</em> to return.
48 *
49 * <p>This method allows the developer to interrogate this binder's intention
50 * which may be different from the {@link ILoggerFactory} instance it is able to
51 * yield in practice. The discrepancy should only occur in case of errors.
52 *
53 * @return the class name of the intended {@link ILoggerFactory} instance
54 */
55 public String getLoggerFactoryClassStr();
56 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import java.util.Map;
27
28 /**
29 * This interface abstracts the service offered by various MDC
30 * implementations.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 * @since 1.4.1
34 */
35 public interface MDCAdapter {
36
37 /**
38 * Put a context value (the <code>val</code> parameter) as identified with
39 * the <code>key</code> parameter into the current thread's context map.
40 * The <code>key</code> parameter cannot be null. The <code>val</code> parameter
41 * can be null only if the underlying implementation supports it.
42 *
43 * <p>If the current thread does not have a context map it is created as a side
44 * effect of this call.
45 */
46 public void put(String key, String val);
47
48 /**
49 * Get the context identified by the <code>key</code> parameter.
50 * The <code>key</code> parameter cannot be null.
51 *
52 * @return the string value identified by the <code>key</code> parameter.
53 */
54 public String get(String key);
55
56 /**
57 * Remove the the context identified by the <code>key</code> parameter.
58 * The <code>key</code> parameter cannot be null.
59 *
60 * <p>
61 * This method does nothing if there is no previous value
62 * associated with <code>key</code>.
63 */
64 public void remove(String key);
65
66 /**
67 * Clear all entries in the MDC.
68 */
69 public void clear();
70
71 /**
72 * Return a copy of the current thread's context map, with keys and
73 * values of type String. Returned value may be null.
74 *
75 * @return A copy of the current thread's context map. May be null.
76 * @since 1.5.1
77 */
78 public Map<String, String> getCopyOfContextMap();
79
80 /**
81 * Set the current thread's context map by first clearing any existing
82 * map and then copying the map passed as parameter. The context map
83 * parameter must only contain keys and values of type String.
84 *
85 * @param contextMap must contain only keys and values of type String
86 *
87 * @since 1.5.1
88 */
89 public void setContextMap(Map<String, String> contextMap);
90 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import java.util.Map;
27
28 /**
29 * This interface abstracts the service offered by various MDC
30 * implementations.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 * @since 1.4.1
34 */
35 public interface MDCAdapter {
36
37 /**
38 * Put a context value (the <code>val</code> parameter) as identified with
39 * the <code>key</code> parameter into the current thread's context map.
40 * The <code>key</code> parameter cannot be null. The <code>val</code> parameter
41 * can be null only if the underlying implementation supports it.
42 *
43 * <p>If the current thread does not have a context map it is created as a side
44 * effect of this call.
45 */
46 public void put(String key, String val);
47
48 /**
49 * Get the context identified by the <code>key</code> parameter.
50 * The <code>key</code> parameter cannot be null.
51 *
52 * @return the string value identified by the <code>key</code> parameter.
53 */
54 public String get(String key);
55
56 /**
57 * Remove the the context identified by the <code>key</code> parameter.
58 * The <code>key</code> parameter cannot be null.
59 *
60 * <p>
61 * This method does nothing if there is no previous value
62 * associated with <code>key</code>.
63 */
64 public void remove(String key);
65
66 /**
67 * Clear all entries in the MDC.
68 */
69 public void clear();
70
71 /**
72 * Return a copy of the current thread's context map, with keys and
73 * values of type String. Returned value may be null.
74 *
75 * @return A copy of the current thread's context map. May be null.
76 * @since 1.5.1
77 */
78 public Map<String, String> getCopyOfContextMap();
79
80 /**
81 * Set the current thread's context map by first clearing any existing
82 * map and then copying the map passed as parameter. The context map
83 * parameter must only contain keys and values of type String.
84 *
85 * @param contextMap must contain only keys and values of type String
86 *
87 * @since 1.5.1
88 */
89 public void setContextMap(Map<String, String> contextMap);
90 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import org.slf4j.IMarkerFactory;
27
28 /**
29 * An internal interface which helps the static {@link org.slf4j.MarkerFactory}
30 * class bind with the appropriate {@link IMarkerFactory} instance.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public interface MarkerFactoryBinder {
35
36 /**
37 * Return the instance of {@link IMarkerFactory} that
38 * {@link org.slf4j.MarkerFactory} class should bind to.
39 *
40 * @return the instance of {@link IMarkerFactory} that
41 * {@link org.slf4j.MarkerFactory} class should bind to.
42 */
43 public IMarkerFactory getMarkerFactory();
44
45 /**
46 * The String form of the {@link IMarkerFactory} object that this
47 * <code>MarkerFactoryBinder</code> instance is <em>intended</em> to return.
48 *
49 * <p>This method allows the developer to interrogate this binder's intention
50 * which may be different from the {@link IMarkerFactory} instance it is able to
51 * return. Such a discrepancy should only occur in case of errors.
52 *
53 * @return the class name of the intended {@link IMarkerFactory} instance
54 */
55 public String getMarkerFactoryClassStr();
56 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import org.slf4j.IMarkerFactory;
27
28 /**
29 * An internal interface which helps the static {@link org.slf4j.MarkerFactory}
30 * class bind with the appropriate {@link IMarkerFactory} instance.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public interface MarkerFactoryBinder {
35
36 /**
37 * Return the instance of {@link IMarkerFactory} that
38 * {@link org.slf4j.MarkerFactory} class should bind to.
39 *
40 * @return the instance of {@link IMarkerFactory} that
41 * {@link org.slf4j.MarkerFactory} class should bind to.
42 */
43 public IMarkerFactory getMarkerFactory();
44
45 /**
46 * The String form of the {@link IMarkerFactory} object that this
47 * <code>MarkerFactoryBinder</code> instance is <em>intended</em> to return.
48 *
49 * <p>This method allows the developer to interrogate this binder's intention
50 * which may be different from the {@link IMarkerFactory} instance it is able to
51 * return. Such a discrepancy should only occur in case of errors.
52 *
53 * @return the class name of the intended {@link IMarkerFactory} instance
54 */
55 public String getMarkerFactoryClassStr();
56 }
0
1 <body>
2
3
4 Classes and interfaces which are internal to SLF4J. Under most
5 circumstances SLF4J users should be oblivious even to the existence of
6 this package.
0
1 <body>
2
3
4 Classes and interfaces which are internal to SLF4J. Under most
5 circumstances SLF4J users should be oblivious even to the existence of
6 this package.
77 </body>
0 Implementation-Title: slf4j-api
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.api
3 Bundle-Name: slf4j-api
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j;version=${parsedVersion.osgiVersion},
7 org.slf4j.spi;version=${parsedVersion.osgiVersion},
8 org.slf4j.helpers;version=${parsedVersion.osgiVersion},
9 org.slf4j.event;version=${parsedVersion.osgiVersion}
10 Import-Package: org.slf4j.impl;version=${slf4j.api.minimum.compatible.version}
0 Implementation-Title: slf4j-api
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.api
3 Bundle-Name: slf4j-api
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j;version=${parsedVersion.osgiVersion},
7 org.slf4j.spi;version=${parsedVersion.osgiVersion},
8 org.slf4j.helpers;version=${parsedVersion.osgiVersion},
9 org.slf4j.event;version=${parsedVersion.osgiVersion}
10 Import-Package: org.slf4j.impl;version=${slf4j.api.minimum.compatible.version}
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.*;
27
28 import java.util.Iterator;
29
30 import org.junit.Test;
31 import org.slf4j.helpers.BasicMarkerFactory;
32
33 /**
34 * Unit test BasicMarker
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 * @author Joern Huxhorn
38 */
39 public class BasicMarkerTest {
40 static final String BLUE_STR = "BLUE";
41 static final String RED_STR = "RED";
42 static final String GREEN_STR = "GREEN";
43 static final String COMP_STR = "COMP";
44 static final String MULTI_COMP_STR = "MULTI_COMP";
45 static final String PARENT_MARKER_STR = "PARENT_MARKER";
46 static final String CHILD_MARKER_STR = "CHILD_MARKER";
47 static final String NOT_CONTAINED_MARKER_STR = "NOT_CONTAINED";
48
49 final IMarkerFactory factory;
50 final Marker blue;
51 final Marker red;
52 final Marker green;
53 final Marker comp;
54 final Marker multiComp;
55
56 short diff = Differentiator.getDiffentiator();
57
58 public BasicMarkerTest() {
59 factory = new BasicMarkerFactory();
60
61 blue = factory.getMarker(BLUE_STR);
62 red = factory.getMarker(RED_STR);
63 green = factory.getMarker(GREEN_STR);
64 comp = factory.getMarker(COMP_STR);
65 comp.add(blue);
66
67 multiComp = factory.getMarker(MULTI_COMP_STR);
68 multiComp.add(green);
69 multiComp.add(comp);
70 }
71
72 @Test
73 public void testPrimitive() {
74 assertEquals(BLUE_STR, blue.getName());
75 assertTrue(blue.contains(blue));
76
77 Marker blue2 = factory.getMarker(BLUE_STR);
78 assertEquals(BLUE_STR, blue2.getName());
79 assertEquals(blue, blue2);
80 assertTrue(blue.contains(blue2));
81 assertTrue(blue2.contains(blue));
82 }
83
84 @Test
85 public void testPrimitiveByName() {
86 assertTrue(blue.contains(BLUE_STR));
87 }
88
89 @Test
90 public void testComposite() {
91 assertTrue(comp.contains(comp));
92 assertTrue(comp.contains(blue));
93 }
94
95 @Test
96 public void testCompositeByName() {
97 assertTrue(comp.contains(COMP_STR));
98 assertTrue(comp.contains(BLUE_STR));
99 }
100
101 @Test
102 public void testMultiComposite() {
103 assertTrue(multiComp.contains(comp));
104 assertTrue(multiComp.contains(blue));
105 assertTrue(multiComp.contains(green));
106 assertFalse(multiComp.contains(red));
107 }
108
109 @Test
110 public void testMultiCompositeByName() {
111 assertTrue(multiComp.contains(COMP_STR));
112 assertTrue(multiComp.contains(BLUE_STR));
113 assertTrue(multiComp.contains(GREEN_STR));
114 assertFalse(multiComp.contains(RED_STR));
115 }
116
117 @Test
118 public void testMultiAdd() {
119 Marker parent = factory.getMarker(PARENT_MARKER_STR);
120 Marker child = factory.getMarker(CHILD_MARKER_STR);
121 for (int i = 0; i < 10; i++) {
122 parent.add(child);
123 }
124
125 // check that the child was added once and only once
126 Iterator<Marker> iterator = parent.iterator();
127 assertTrue(iterator.hasNext());
128 assertEquals(CHILD_MARKER_STR, iterator.next().toString());
129 assertFalse(iterator.hasNext());
130 }
131
132 @Test
133 public void testAddRemove() {
134 final String NEW_PREFIX = "NEW_";
135 Marker parent = factory.getMarker(NEW_PREFIX + PARENT_MARKER_STR);
136 Marker child = factory.getMarker(NEW_PREFIX + CHILD_MARKER_STR);
137 assertFalse(parent.contains(child));
138 assertFalse(parent.contains(NEW_PREFIX + CHILD_MARKER_STR));
139 assertFalse(parent.remove(child));
140
141 parent.add(child);
142
143 assertTrue(parent.contains(child));
144 assertTrue(parent.contains(NEW_PREFIX + CHILD_MARKER_STR));
145
146 assertTrue(parent.remove(child));
147
148 assertFalse(parent.contains(child));
149 assertFalse(parent.contains(NEW_PREFIX + CHILD_MARKER_STR));
150 assertFalse(parent.remove(child));
151 }
152
153 @Test
154 public void testSelfRecursion() {
155 final String diffPrefix = "NEW_" + diff;
156 final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR;
157 final String NOT_CONTAINED_NAME = diffPrefix + NOT_CONTAINED_MARKER_STR;
158 Marker parent = factory.getMarker(PARENT_NAME);
159 Marker notContained = factory.getMarker(NOT_CONTAINED_NAME);
160 parent.add(parent);
161 assertTrue(parent.contains(parent));
162 assertTrue(parent.contains(PARENT_NAME));
163 assertFalse(parent.contains(notContained));
164 assertFalse(parent.contains(NOT_CONTAINED_MARKER_STR));
165 }
166
167 @Test
168 public void testIndirectRecursion() {
169 final String diffPrefix = "NEW_" + diff;
170 final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR;
171 final String CHILD_NAME = diffPrefix + CHILD_MARKER_STR;
172 final String NOT_CONTAINED_NAME = diffPrefix + NOT_CONTAINED_MARKER_STR;
173
174 Marker parent = factory.getMarker(PARENT_NAME);
175 Marker child = factory.getMarker(CHILD_NAME);
176 Marker notContained = factory.getMarker(NOT_CONTAINED_NAME);
177
178 parent.add(child);
179 child.add(parent);
180 assertTrue(parent.contains(parent));
181 assertTrue(parent.contains(child));
182 assertTrue(parent.contains(PARENT_NAME));
183 assertTrue(parent.contains(CHILD_NAME));
184 assertFalse(parent.contains(notContained));
185 assertFalse(parent.contains(NOT_CONTAINED_MARKER_STR));
186 }
187
188 @Test
189 public void testHomonyms() {
190 final String diffPrefix = "homonym" + diff;
191 final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR;
192 final String CHILD_NAME = diffPrefix + CHILD_MARKER_STR;
193 Marker parent = factory.getMarker(PARENT_NAME);
194 Marker child = factory.getMarker(CHILD_NAME);
195 parent.add(child);
196
197 IMarkerFactory otherFactory = new BasicMarkerFactory();
198 Marker otherParent = otherFactory.getMarker(PARENT_NAME);
199 Marker otherChild = otherFactory.getMarker(CHILD_NAME);
200
201 assertTrue(parent.contains(otherParent));
202 assertTrue(parent.contains(otherChild));
203
204 assertTrue(parent.remove(otherChild));
205 }
206
207 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.*;
27
28 import java.util.Iterator;
29
30 import org.junit.Test;
31 import org.slf4j.helpers.BasicMarkerFactory;
32
33 /**
34 * Unit test BasicMarker
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 * @author Joern Huxhorn
38 */
39 public class BasicMarkerTest {
40 static final String BLUE_STR = "BLUE";
41 static final String RED_STR = "RED";
42 static final String GREEN_STR = "GREEN";
43 static final String COMP_STR = "COMP";
44 static final String MULTI_COMP_STR = "MULTI_COMP";
45 static final String PARENT_MARKER_STR = "PARENT_MARKER";
46 static final String CHILD_MARKER_STR = "CHILD_MARKER";
47 static final String NOT_CONTAINED_MARKER_STR = "NOT_CONTAINED";
48
49 final IMarkerFactory factory;
50 final Marker blue;
51 final Marker red;
52 final Marker green;
53 final Marker comp;
54 final Marker multiComp;
55
56 short diff = Differentiator.getDiffentiator();
57
58 public BasicMarkerTest() {
59 factory = new BasicMarkerFactory();
60
61 blue = factory.getMarker(BLUE_STR);
62 red = factory.getMarker(RED_STR);
63 green = factory.getMarker(GREEN_STR);
64 comp = factory.getMarker(COMP_STR);
65 comp.add(blue);
66
67 multiComp = factory.getMarker(MULTI_COMP_STR);
68 multiComp.add(green);
69 multiComp.add(comp);
70 }
71
72 @Test
73 public void testPrimitive() {
74 assertEquals(BLUE_STR, blue.getName());
75 assertTrue(blue.contains(blue));
76
77 Marker blue2 = factory.getMarker(BLUE_STR);
78 assertEquals(BLUE_STR, blue2.getName());
79 assertEquals(blue, blue2);
80 assertTrue(blue.contains(blue2));
81 assertTrue(blue2.contains(blue));
82 }
83
84 @Test
85 public void testPrimitiveByName() {
86 assertTrue(blue.contains(BLUE_STR));
87 }
88
89 @Test
90 public void testComposite() {
91 assertTrue(comp.contains(comp));
92 assertTrue(comp.contains(blue));
93 }
94
95 @Test
96 public void testCompositeByName() {
97 assertTrue(comp.contains(COMP_STR));
98 assertTrue(comp.contains(BLUE_STR));
99 }
100
101 @Test
102 public void testMultiComposite() {
103 assertTrue(multiComp.contains(comp));
104 assertTrue(multiComp.contains(blue));
105 assertTrue(multiComp.contains(green));
106 assertFalse(multiComp.contains(red));
107 }
108
109 @Test
110 public void testMultiCompositeByName() {
111 assertTrue(multiComp.contains(COMP_STR));
112 assertTrue(multiComp.contains(BLUE_STR));
113 assertTrue(multiComp.contains(GREEN_STR));
114 assertFalse(multiComp.contains(RED_STR));
115 }
116
117 @Test
118 public void testMultiAdd() {
119 Marker parent = factory.getMarker(PARENT_MARKER_STR);
120 Marker child = factory.getMarker(CHILD_MARKER_STR);
121 for (int i = 0; i < 10; i++) {
122 parent.add(child);
123 }
124
125 // check that the child was added once and only once
126 Iterator<Marker> iterator = parent.iterator();
127 assertTrue(iterator.hasNext());
128 assertEquals(CHILD_MARKER_STR, iterator.next().toString());
129 assertFalse(iterator.hasNext());
130 }
131
132 @Test
133 public void testAddRemove() {
134 final String NEW_PREFIX = "NEW_";
135 Marker parent = factory.getMarker(NEW_PREFIX + PARENT_MARKER_STR);
136 Marker child = factory.getMarker(NEW_PREFIX + CHILD_MARKER_STR);
137 assertFalse(parent.contains(child));
138 assertFalse(parent.contains(NEW_PREFIX + CHILD_MARKER_STR));
139 assertFalse(parent.remove(child));
140
141 parent.add(child);
142
143 assertTrue(parent.contains(child));
144 assertTrue(parent.contains(NEW_PREFIX + CHILD_MARKER_STR));
145
146 assertTrue(parent.remove(child));
147
148 assertFalse(parent.contains(child));
149 assertFalse(parent.contains(NEW_PREFIX + CHILD_MARKER_STR));
150 assertFalse(parent.remove(child));
151 }
152
153 @Test
154 public void testSelfRecursion() {
155 final String diffPrefix = "NEW_" + diff;
156 final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR;
157 final String NOT_CONTAINED_NAME = diffPrefix + NOT_CONTAINED_MARKER_STR;
158 Marker parent = factory.getMarker(PARENT_NAME);
159 Marker notContained = factory.getMarker(NOT_CONTAINED_NAME);
160 parent.add(parent);
161 assertTrue(parent.contains(parent));
162 assertTrue(parent.contains(PARENT_NAME));
163 assertFalse(parent.contains(notContained));
164 assertFalse(parent.contains(NOT_CONTAINED_MARKER_STR));
165 }
166
167 @Test
168 public void testIndirectRecursion() {
169 final String diffPrefix = "NEW_" + diff;
170 final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR;
171 final String CHILD_NAME = diffPrefix + CHILD_MARKER_STR;
172 final String NOT_CONTAINED_NAME = diffPrefix + NOT_CONTAINED_MARKER_STR;
173
174 Marker parent = factory.getMarker(PARENT_NAME);
175 Marker child = factory.getMarker(CHILD_NAME);
176 Marker notContained = factory.getMarker(NOT_CONTAINED_NAME);
177
178 parent.add(child);
179 child.add(parent);
180 assertTrue(parent.contains(parent));
181 assertTrue(parent.contains(child));
182 assertTrue(parent.contains(PARENT_NAME));
183 assertTrue(parent.contains(CHILD_NAME));
184 assertFalse(parent.contains(notContained));
185 assertFalse(parent.contains(NOT_CONTAINED_MARKER_STR));
186 }
187
188 @Test
189 public void testHomonyms() {
190 final String diffPrefix = "homonym" + diff;
191 final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR;
192 final String CHILD_NAME = diffPrefix + CHILD_MARKER_STR;
193 Marker parent = factory.getMarker(PARENT_NAME);
194 Marker child = factory.getMarker(CHILD_NAME);
195 parent.add(child);
196
197 IMarkerFactory otherFactory = new BasicMarkerFactory();
198 Marker otherParent = otherFactory.getMarker(PARENT_NAME);
199 Marker otherChild = otherFactory.getMarker(CHILD_NAME);
200
201 assertTrue(parent.contains(otherParent));
202 assertTrue(parent.contains(otherChild));
203
204 assertTrue(parent.remove(otherChild));
205 }
206
207 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j;
26
27 import java.util.Random;
28
29 public class Differentiator {
30
31 static Random random = new Random(System.currentTimeMillis());
32
33 static public short getDiffentiator() {
34 return (short) random.nextInt(Short.MAX_VALUE);
35 }
36 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j;
26
27 import java.util.Random;
28
29 public class Differentiator {
30
31 static Random random = new Random(System.currentTimeMillis());
32
33 static public short getDiffentiator() {
34 return (short) random.nextInt(Short.MAX_VALUE);
35 }
36 }
0 package org.slf4j;
1
2 import java.util.concurrent.BrokenBarrierException;
3 import java.util.concurrent.CyclicBarrier;
4
5 /**
6 * This class demonstrates that threads accessing the STATE variable always see a consistent value.
7 *
8 * During ongoing initialization the observed value is either ONGOING_INITIALIZATION
9 * or one of {SUCCESS, FAILURE}.
10 *
11 * Post initialization the observed value is always one of {SUCCESS, FAILURE}.
12 *
13 * See also http://jira.qos.ch/browse/SLF4J-167
14 *
15 * @author ceki
16 *
17 */
18 public class DoubleCheckedInt {
19
20 final static int THREAD_COUNT = 10 + Runtime.getRuntime().availableProcessors() * 2;
21 final static int UNINITIALIZED_STATE = 0;
22 final static int ONGOING_INITIALIZATION = 1;
23 final static int SUCCESS = 2;
24 final static int FAILURE = 3;
25 final static int NUMBER_OF_STATES = FAILURE + 1;
26
27 private static int STATE = UNINITIALIZED_STATE;
28
29 public static int getState() {
30 if (STATE == 0) {
31 synchronized (DoubleCheckedInt.class) {
32 if (STATE == UNINITIALIZED_STATE) {
33 STATE = ONGOING_INITIALIZATION;
34 long r = System.nanoTime();
35 try {
36 Thread.sleep(10);
37 } catch (InterruptedException e) {
38 }
39 if (r % 2 == 0) {
40 STATE = SUCCESS;
41 } else {
42 STATE = FAILURE;
43 }
44 }
45 }
46 }
47 return STATE;
48 }
49
50 static public void main(String[] args) throws InterruptedException, BrokenBarrierException {
51 StateAccessingThread[] preInitializationThreads = harness();
52 check(preInitializationThreads, false);
53
54 System.out.println("============");
55 StateAccessingThread[] postInitializationThreads = harness();
56 check(postInitializationThreads, true);
57 }
58
59 private static StateAccessingThread[] harness() throws InterruptedException, BrokenBarrierException {
60 StateAccessingThread[] threads = new StateAccessingThread[THREAD_COUNT];
61 final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1);
62 for (int i = 0; i < THREAD_COUNT; i++) {
63 threads[i] = new StateAccessingThread(barrier);
64 threads[i].start();
65 }
66
67 barrier.await();
68 for (int i = 0; i < THREAD_COUNT; i++) {
69 threads[i].join();
70 }
71 return threads;
72 }
73
74 private static void check(StateAccessingThread[] threads, boolean postInit) {
75
76 int[] stateCount = getStateCount(threads);
77 printStateCount(stateCount);
78
79 if (stateCount[UNINITIALIZED_STATE] != 0) {
80 throw new IllegalStateException("getState() should never return a zero value");
81 }
82
83 if (stateCount[SUCCESS] != 0 && stateCount[FAILURE] != 0) {
84 throw new IllegalStateException("getState() should return consistent values");
85 }
86
87 if (postInit) {
88 if (stateCount[SUCCESS] != THREAD_COUNT && stateCount[FAILURE] != THREAD_COUNT) {
89 throw new IllegalStateException("getState() should return consistent values");
90 }
91 }
92
93 }
94
95 private static void printStateCount(int[] stateCount) {
96 for (int i = 0; i < NUMBER_OF_STATES; i++) {
97 switch (i) {
98 case UNINITIALIZED_STATE:
99 System.out.println("UNINITIALIZED_STATE count: " + stateCount[i]);
100 break;
101 case ONGOING_INITIALIZATION:
102 System.out.println("ONGOING_INITIALIZATION count: " + stateCount[i]);
103 break;
104 case SUCCESS:
105 System.out.println("SUCCESS count: " + stateCount[i]);
106 break;
107 case FAILURE:
108 System.out.println("FAILURE count: " + stateCount[i]);
109 break;
110 }
111 }
112 }
113
114 private static int[] getStateCount(StateAccessingThread[] threads) {
115 int[] valCount = new int[NUMBER_OF_STATES];
116 for (int i = 0; i < threads.length; i++) {
117 int val = threads[i].state;
118 valCount[val] = valCount[val] + 1;
119 }
120 return valCount;
121 }
122
123 static class StateAccessingThread extends Thread {
124 public int state = -1;
125 final CyclicBarrier barrier;
126
127 StateAccessingThread(CyclicBarrier barrier) {
128 this.barrier = barrier;
129 }
130
131 public void run() {
132 try {
133 barrier.await();
134 } catch (Exception e) {
135 e.printStackTrace();
136 }
137 state = DoubleCheckedInt.getState();
138 }
139 };
140 }
0 package org.slf4j;
1
2 import java.util.concurrent.BrokenBarrierException;
3 import java.util.concurrent.CyclicBarrier;
4
5 /**
6 * This class demonstrates that threads accessing the STATE variable always see a consistent value.
7 *
8 * During ongoing initialization the observed value is either ONGOING_INITIALIZATION
9 * or one of {SUCCESS, FAILURE}.
10 *
11 * Post initialization the observed value is always one of {SUCCESS, FAILURE}.
12 *
13 * See also http://jira.qos.ch/browse/SLF4J-167
14 *
15 * @author ceki
16 *
17 */
18 public class DoubleCheckedInt {
19
20 final static int THREAD_COUNT = 10 + Runtime.getRuntime().availableProcessors() * 2;
21 final static int UNINITIALIZED_STATE = 0;
22 final static int ONGOING_INITIALIZATION = 1;
23 final static int SUCCESS = 2;
24 final static int FAILURE = 3;
25 final static int NUMBER_OF_STATES = FAILURE + 1;
26
27 private static int STATE = UNINITIALIZED_STATE;
28
29 public static int getState() {
30 if (STATE == 0) {
31 synchronized (DoubleCheckedInt.class) {
32 if (STATE == UNINITIALIZED_STATE) {
33 STATE = ONGOING_INITIALIZATION;
34 long r = System.nanoTime();
35 try {
36 Thread.sleep(10);
37 } catch (InterruptedException e) {
38 }
39 if (r % 2 == 0) {
40 STATE = SUCCESS;
41 } else {
42 STATE = FAILURE;
43 }
44 }
45 }
46 }
47 return STATE;
48 }
49
50 static public void main(String[] args) throws InterruptedException, BrokenBarrierException {
51 StateAccessingThread[] preInitializationThreads = harness();
52 check(preInitializationThreads, false);
53
54 System.out.println("============");
55 StateAccessingThread[] postInitializationThreads = harness();
56 check(postInitializationThreads, true);
57 }
58
59 private static StateAccessingThread[] harness() throws InterruptedException, BrokenBarrierException {
60 StateAccessingThread[] threads = new StateAccessingThread[THREAD_COUNT];
61 final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1);
62 for (int i = 0; i < THREAD_COUNT; i++) {
63 threads[i] = new StateAccessingThread(barrier);
64 threads[i].start();
65 }
66
67 barrier.await();
68 for (int i = 0; i < THREAD_COUNT; i++) {
69 threads[i].join();
70 }
71 return threads;
72 }
73
74 private static void check(StateAccessingThread[] threads, boolean postInit) {
75
76 int[] stateCount = getStateCount(threads);
77 printStateCount(stateCount);
78
79 if (stateCount[UNINITIALIZED_STATE] != 0) {
80 throw new IllegalStateException("getState() should never return a zero value");
81 }
82
83 if (stateCount[SUCCESS] != 0 && stateCount[FAILURE] != 0) {
84 throw new IllegalStateException("getState() should return consistent values");
85 }
86
87 if (postInit) {
88 if (stateCount[SUCCESS] != THREAD_COUNT && stateCount[FAILURE] != THREAD_COUNT) {
89 throw new IllegalStateException("getState() should return consistent values");
90 }
91 }
92
93 }
94
95 private static void printStateCount(int[] stateCount) {
96 for (int i = 0; i < NUMBER_OF_STATES; i++) {
97 switch (i) {
98 case UNINITIALIZED_STATE:
99 System.out.println("UNINITIALIZED_STATE count: " + stateCount[i]);
100 break;
101 case ONGOING_INITIALIZATION:
102 System.out.println("ONGOING_INITIALIZATION count: " + stateCount[i]);
103 break;
104 case SUCCESS:
105 System.out.println("SUCCESS count: " + stateCount[i]);
106 break;
107 case FAILURE:
108 System.out.println("FAILURE count: " + stateCount[i]);
109 break;
110 }
111 }
112 }
113
114 private static int[] getStateCount(StateAccessingThread[] threads) {
115 int[] valCount = new int[NUMBER_OF_STATES];
116 for (int i = 0; i < threads.length; i++) {
117 int val = threads[i].state;
118 valCount[val] = valCount[val] + 1;
119 }
120 return valCount;
121 }
122
123 static class StateAccessingThread extends Thread {
124 public int state = -1;
125 final CyclicBarrier barrier;
126
127 StateAccessingThread(CyclicBarrier barrier) {
128 this.barrier = barrier;
129 }
130
131 public void run() {
132 try {
133 barrier.await();
134 } catch (Exception e) {
135 e.printStackTrace();
136 }
137 state = DoubleCheckedInt.getState();
138 }
139 };
140 }
0 /**
1 * Copyright (c) 2004-2016 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.util.List;
27 import java.util.concurrent.CyclicBarrier;
28 import java.util.concurrent.atomic.AtomicLong;
29
30 public class LoggerAccessingThread extends Thread {
31 private static int LOOP_LEN = 64;
32
33 final CyclicBarrier barrier;
34 final int count;
35 final AtomicLong eventCount;
36 List<Logger> loggerList;
37
38 public LoggerAccessingThread(final CyclicBarrier barrier, List<Logger> loggerList, final int count, final AtomicLong eventCount) {
39 this.barrier = barrier;
40 this.loggerList = loggerList;
41 this.count = count;
42 this.eventCount = eventCount;
43 }
44
45 public void run() {
46 try {
47 barrier.await();
48 } catch (Exception e) {
49 e.printStackTrace();
50 }
51
52 String loggerNamePrefix = this.getClass().getName();
53 for (int i = 0; i < LOOP_LEN; i++) {
54 Logger logger = LoggerFactory.getLogger(loggerNamePrefix + "-" + count + "-" + i);
55 loggerList.add(logger);
56 Thread.yield();
57 logger.info("in run method");
58 eventCount.getAndIncrement();
59 }
60 }
61 }
0 /**
1 * Copyright (c) 2004-2016 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.util.List;
27 import java.util.concurrent.CyclicBarrier;
28 import java.util.concurrent.atomic.AtomicLong;
29
30 public class LoggerAccessingThread extends Thread {
31 private static int LOOP_LEN = 64;
32
33 final CyclicBarrier barrier;
34 final int count;
35 final AtomicLong eventCount;
36 List<Logger> loggerList;
37
38 public LoggerAccessingThread(final CyclicBarrier barrier, List<Logger> loggerList, final int count, final AtomicLong eventCount) {
39 this.barrier = barrier;
40 this.loggerList = loggerList;
41 this.count = count;
42 this.eventCount = eventCount;
43 }
44
45 public void run() {
46 try {
47 barrier.await();
48 } catch (Exception e) {
49 e.printStackTrace();
50 }
51
52 String loggerNamePrefix = this.getClass().getName();
53 for (int i = 0; i < LOOP_LEN; i++) {
54 Logger logger = LoggerFactory.getLogger(loggerNamePrefix + "-" + count + "-" + i);
55 loggerList.add(logger);
56 Thread.yield();
57 logger.info("in run method");
58 eventCount.getAndIncrement();
59 }
60 }
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertNull;
27 import static org.junit.Assert.assertTrue;
28
29 import java.util.Random;
30
31 import org.junit.Test;
32 import org.slf4j.helpers.BasicMarker;
33 import org.slf4j.helpers.NOPLogger;
34
35 public class NoBindingTest {
36
37 int diff = new Random().nextInt(10000);
38
39 @Test
40 public void testLogger() {
41 Logger logger = LoggerFactory.getLogger(NoBindingTest.class);
42 logger.debug("hello" + diff);
43 assertTrue(logger instanceof NOPLogger);
44 }
45
46 @Test
47 public void testMDC() {
48 MDC.put("k" + diff, "v");
49 assertNull(MDC.get("k"));
50 }
51
52 @Test
53 public void testMarker() {
54 Marker m = MarkerFactory.getMarker("a" + diff);
55 assertTrue(m instanceof BasicMarker);
56 }
57 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertNull;
27 import static org.junit.Assert.assertTrue;
28
29 import java.util.Random;
30
31 import org.junit.Test;
32 import org.slf4j.helpers.BasicMarker;
33 import org.slf4j.helpers.NOPLogger;
34
35 public class NoBindingTest {
36
37 int diff = new Random().nextInt(10000);
38
39 @Test
40 public void testLogger() {
41 Logger logger = LoggerFactory.getLogger(NoBindingTest.class);
42 logger.debug("hello" + diff);
43 assertTrue(logger instanceof NOPLogger);
44 }
45
46 @Test
47 public void testMDC() {
48 MDC.put("k" + diff, "v");
49 assertNull(MDC.get("k"));
50 }
51
52 @Test
53 public void testMarker() {
54 Marker m = MarkerFactory.getMarker("a" + diff);
55 assertTrue(m instanceof BasicMarker);
56 }
57 }
0 /**
1 * Copyright (c) 2004-2013 QOS.ch, Copyright (C) 2015 Google Inc.
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23
24 package org.slf4j.helpers;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertFalse;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.fail;
30
31 import java.lang.Thread.UncaughtExceptionHandler;
32 import java.util.Map;
33
34 import org.junit.After;
35 import org.junit.Test;
36 import org.slf4j.spi.MDCAdapter;
37
38 /**
39 * Tests for {@link BasicMDCAdapter}
40 *
41 * @author Lukasz Cwik
42 */
43 public class BasicMDCAdapterTest {
44 MDCAdapter mdc = new BasicMDCAdapter();
45
46 @After
47 public void tearDown() throws Exception {
48 mdc.clear();
49 }
50
51 @Test
52 public void testSettingAndGettingWithMDC() {
53 assertNull(mdc.get("testKey"));
54 mdc.put("testKey", "testValue");
55 assertEquals(mdc.get("testKey"), "testValue");
56 }
57
58 @Test
59 public void testOverwritingAKeyInMDC() {
60 assertNull(mdc.get("testKey"));
61 mdc.put("testKey", "testValue");
62 mdc.put("testKey", "differentTestValue");
63 assertEquals(mdc.get("testKey"), "differentTestValue");
64 }
65
66 @Test
67 public void testClearingMDC() {
68 mdc.put("testKey", "testValue");
69 assertFalse(mdc.getCopyOfContextMap().isEmpty());
70 mdc.clear();
71 assertNull(mdc.getCopyOfContextMap());
72 }
73
74 @Test
75 public void testGetCopyOfContextMapFromMDC() {
76 mdc.put("testKey", "testValue");
77 Map<String, String> copy = mdc.getCopyOfContextMap();
78 mdc.put("anotherTestKey", "anotherTestValue");
79 assertFalse(copy.size() == mdc.getCopyOfContextMap().size());
80 }
81
82 @Test
83 public void testMDCInheritsValuesFromParentThread() throws Exception {
84 mdc.put("parentKey", "parentValue");
85 runAndWait(new Runnable() {
86 public void run() {
87 mdc.put("childKey", "childValue");
88 assertEquals("parentValue", mdc.get("parentKey"));
89 }
90 });
91 }
92
93 @Test
94 public void testMDCDoesntGetValuesFromChildThread() throws Exception {
95 mdc.put("parentKey", "parentValue");
96 runAndWait(new Runnable() {
97 public void run() {
98 mdc.put("childKey", "childValue");
99 }
100 });
101 assertEquals("parentValue", mdc.get("parentKey"));
102 assertNull(mdc.get("childKey"));
103 }
104
105 @Test
106 public void testMDCChildThreadCanOverwriteParentThread() throws Exception {
107 mdc.put("sharedKey", "parentValue");
108 runAndWait(new Runnable() {
109 public void run() {
110 assertEquals("parentValue", mdc.get("sharedKey"));
111 mdc.put("sharedKey", "childValue");
112 assertEquals("childValue", mdc.get("sharedKey"));
113 }
114 });
115 assertEquals("parentValue", mdc.get("sharedKey"));
116 }
117
118 private void runAndWait(Runnable runnable) throws Exception {
119 RecordingExceptionHandler handler = new RecordingExceptionHandler();
120 Thread thread = new Thread(runnable);
121 thread.setUncaughtExceptionHandler(handler);
122 thread.start();
123 try {
124 thread.join();
125 } catch (Throwable t) {
126 fail("Unexpected failure in child thread:" + t.getMessage());
127 }
128 assertFalse(handler.getMessage(), handler.hadException());
129 }
130
131 /** A {@link UncaughtExceptionHandler} that records whether the thread threw an exception. */
132 private static class RecordingExceptionHandler implements UncaughtExceptionHandler {
133 private Throwable exception;
134
135 public void uncaughtException(Thread t, Throwable e) {
136 exception = e;
137 }
138
139 boolean hadException() {
140 return exception != null;
141 }
142
143 String getMessage() {
144 return exception != null ? exception.getMessage() : "";
145 }
146 }
147 }
0 /**
1 * Copyright (c) 2004-2013 QOS.ch, Copyright (C) 2015 Google Inc.
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23
24 package org.slf4j.helpers;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertFalse;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.fail;
30
31 import java.lang.Thread.UncaughtExceptionHandler;
32 import java.util.Map;
33
34 import org.junit.After;
35 import org.junit.Test;
36 import org.slf4j.spi.MDCAdapter;
37
38 /**
39 * Tests for {@link BasicMDCAdapter}
40 *
41 * @author Lukasz Cwik
42 */
43 public class BasicMDCAdapterTest {
44 MDCAdapter mdc = new BasicMDCAdapter();
45
46 @After
47 public void tearDown() throws Exception {
48 mdc.clear();
49 }
50
51 @Test
52 public void testSettingAndGettingWithMDC() {
53 assertNull(mdc.get("testKey"));
54 mdc.put("testKey", "testValue");
55 assertEquals(mdc.get("testKey"), "testValue");
56 }
57
58 @Test
59 public void testOverwritingAKeyInMDC() {
60 assertNull(mdc.get("testKey"));
61 mdc.put("testKey", "testValue");
62 mdc.put("testKey", "differentTestValue");
63 assertEquals(mdc.get("testKey"), "differentTestValue");
64 }
65
66 @Test
67 public void testClearingMDC() {
68 mdc.put("testKey", "testValue");
69 assertFalse(mdc.getCopyOfContextMap().isEmpty());
70 mdc.clear();
71 assertNull(mdc.getCopyOfContextMap());
72 }
73
74 @Test
75 public void testGetCopyOfContextMapFromMDC() {
76 mdc.put("testKey", "testValue");
77 Map<String, String> copy = mdc.getCopyOfContextMap();
78 mdc.put("anotherTestKey", "anotherTestValue");
79 assertFalse(copy.size() == mdc.getCopyOfContextMap().size());
80 }
81
82 @Test
83 public void testMDCInheritsValuesFromParentThread() throws Exception {
84 mdc.put("parentKey", "parentValue");
85 runAndWait(new Runnable() {
86 public void run() {
87 mdc.put("childKey", "childValue");
88 assertEquals("parentValue", mdc.get("parentKey"));
89 }
90 });
91 }
92
93 @Test
94 public void testMDCDoesntGetValuesFromChildThread() throws Exception {
95 mdc.put("parentKey", "parentValue");
96 runAndWait(new Runnable() {
97 public void run() {
98 mdc.put("childKey", "childValue");
99 }
100 });
101 assertEquals("parentValue", mdc.get("parentKey"));
102 assertNull(mdc.get("childKey"));
103 }
104
105 @Test
106 public void testMDCChildThreadCanOverwriteParentThread() throws Exception {
107 mdc.put("sharedKey", "parentValue");
108 runAndWait(new Runnable() {
109 public void run() {
110 assertEquals("parentValue", mdc.get("sharedKey"));
111 mdc.put("sharedKey", "childValue");
112 assertEquals("childValue", mdc.get("sharedKey"));
113 }
114 });
115 assertEquals("parentValue", mdc.get("sharedKey"));
116 }
117
118 private void runAndWait(Runnable runnable) throws Exception {
119 RecordingExceptionHandler handler = new RecordingExceptionHandler();
120 Thread thread = new Thread(runnable);
121 thread.setUncaughtExceptionHandler(handler);
122 thread.start();
123 try {
124 thread.join();
125 } catch (Throwable t) {
126 fail("Unexpected failure in child thread:" + t.getMessage());
127 }
128 assertFalse(handler.getMessage(), handler.hadException());
129 }
130
131 /** A {@link UncaughtExceptionHandler} that records whether the thread threw an exception. */
132 private static class RecordingExceptionHandler implements UncaughtExceptionHandler {
133 private Throwable exception;
134
135 public void uncaughtException(Thread t, Throwable e) {
136 exception = e;
137 }
138
139 boolean hadException() {
140 return exception != null;
141 }
142
143 String getMessage() {
144 return exception != null ? exception.getMessage() : "";
145 }
146 }
147 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import junit.framework.AssertionFailedError;
27
28 /**
29 * BogoPerf is used to check that the time required to perform a certain
30 * operation does not deteriorate over time. BogoPerf adjusts to the CPU speed
31 * and capabilities of the host.
32 *
33 * @author Ceki G&uuml;lc&uuml;
34 *
35 */
36 public class BogoPerf {
37
38 private static long NANOS_IN_ONE_SECOND = 1000 * 1000 * 1000;
39 private static int INITIAL_N = 1000;
40 private static int LAST_N = 100;
41 private static int SLACK_FACTOR = 3;
42
43 static {
44 // let the JIT warm up
45 computeBogoIPS(INITIAL_N);
46 double bogo_ips = computeBogoIPS(INITIAL_N);
47 System.out.println("Host runs at " + bogo_ips + " BIPS");
48 }
49
50 /**
51 * Compute bogoInstructions per second
52 * <p>
53 * on a 3.2 Ghz Pentium D CPU (around 2007), we obtain about 9'000 bogoIPS.
54 *
55 * @param N
56 * number of bogoInstructions to average over in order to
57 * compute the result
58 * @return bogo Instructions Per Second
59 */
60 private static double computeBogoIPS(int N) {
61 long begin = System.nanoTime();
62
63 for (int i = 0; i < N; i++) {
64 bogoInstruction();
65 }
66 long end = System.nanoTime();
67
68 // duration
69 double D = end - begin;
70 // average duration per instruction
71 double avgDPIS = D / N;
72 // System.out.println(D + " nanos for " + N + " instructions");
73 // System.out.println(avgD + " nanos per instruction");
74
75 double bogoIPS = NANOS_IN_ONE_SECOND / avgDPIS;
76 // System.out.println(bogoIPS + " bogoIPS");
77
78 return bogoIPS;
79 }
80
81 private static void bogoInstruction() {
82 // use our own random number generator, independent of the host JDK
83 MyRandom myRandom = new MyRandom(100);
84 int len = 150;
85 int[] intArray = new int[len];
86 for (int i = 0; i < len; i++) {
87 intArray[i] = myRandom.nextInt();
88 }
89 // use our own sort algorithm, independent of the host JDK
90 BubbleSort.sort(intArray);
91 }
92
93 /**
94 * Computed the BogoIPS for this host CPU.
95 *
96 * @return
97 */
98 public static double currentBIPS() {
99 return computeBogoIPS(LAST_N);
100 }
101
102 static double min(double a, double b) {
103 return (a <= b) ? a : b;
104 }
105
106 /**
107 * Assertion used for values that <b>decrease</b> with faster CPUs, typically
108 * the time (duration) needed to perform a task.
109 *
110 * @param currentDuration
111 * @param referenceDuration
112 * @param referenceBIPS
113 * @throws AssertionFailedError
114 */
115 public static void assertDuration(double currentDuration, long referenceDuration, double referenceBIPS) throws AssertionFailedError {
116 double ajustedDuration = adjustExpectedDuration(referenceDuration, referenceBIPS);
117 if (currentDuration > ajustedDuration * SLACK_FACTOR) {
118 throw new AssertionFailedError("current duration " + currentDuration + " exceeded expected " + ajustedDuration + " (adjusted reference), "
119 + referenceDuration + " (raw reference)");
120 }
121 }
122
123 /**
124 * Assertion used for values that <b>increase<b> with faster CPUs, typically
125 * the number of operations accomplished per unit of time.
126 *
127 * @param currentPerformance
128 * @param referencePerformance
129 * @param referenceBIPS
130 * @throws AssertionFailedError
131 */
132 public static void assertPerformance(double currentPerformance, long referencePerformance, double referenceBIPS) throws AssertionFailedError {
133 double ajustedPerf = adjustExpectedPerformance(referencePerformance, referenceBIPS);
134 if (currentPerformance * SLACK_FACTOR < ajustedPerf) {
135 throw new AssertionFailedError(currentPerformance + " below expected " + ajustedPerf + " (adjusted), " + referencePerformance + " (raw)");
136 }
137 }
138
139 private static double adjustExpectedPerformance(long referenceDuration, double referenceBIPS) {
140 double currentBIPS = currentBIPS();
141 return referenceDuration * (currentBIPS / referenceBIPS);
142 }
143
144 private static double adjustExpectedDuration(long referenceDuration, double referenceBIPS) {
145 double currentBIPS = currentBIPS();
146 System.out.println("currentBIPS=" + currentBIPS + " BIPS");
147 return referenceDuration * (referenceBIPS / currentBIPS);
148 }
149 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import junit.framework.AssertionFailedError;
27
28 /**
29 * BogoPerf is used to check that the time required to perform a certain
30 * operation does not deteriorate over time. BogoPerf adjusts to the CPU speed
31 * and capabilities of the host.
32 *
33 * @author Ceki G&uuml;lc&uuml;
34 *
35 */
36 public class BogoPerf {
37
38 private static long NANOS_IN_ONE_SECOND = 1000 * 1000 * 1000;
39 private static int INITIAL_N = 1000;
40 private static int LAST_N = 100;
41 private static int SLACK_FACTOR = 3;
42
43 static {
44 // let the JIT warm up
45 computeBogoIPS(INITIAL_N);
46 double bogo_ips = computeBogoIPS(INITIAL_N);
47 System.out.println("Host runs at " + bogo_ips + " BIPS");
48 }
49
50 /**
51 * Compute bogoInstructions per second
52 * <p>
53 * on a 3.2 Ghz Pentium D CPU (around 2007), we obtain about 9'000 bogoIPS.
54 *
55 * @param N
56 * number of bogoInstructions to average over in order to
57 * compute the result
58 * @return bogo Instructions Per Second
59 */
60 private static double computeBogoIPS(int N) {
61 long begin = System.nanoTime();
62
63 for (int i = 0; i < N; i++) {
64 bogoInstruction();
65 }
66 long end = System.nanoTime();
67
68 // duration
69 double D = end - begin;
70 // average duration per instruction
71 double avgDPIS = D / N;
72 // System.out.println(D + " nanos for " + N + " instructions");
73 // System.out.println(avgD + " nanos per instruction");
74
75 double bogoIPS = NANOS_IN_ONE_SECOND / avgDPIS;
76 // System.out.println(bogoIPS + " bogoIPS");
77
78 return bogoIPS;
79 }
80
81 private static void bogoInstruction() {
82 // use our own random number generator, independent of the host JDK
83 MyRandom myRandom = new MyRandom(100);
84 int len = 150;
85 int[] intArray = new int[len];
86 for (int i = 0; i < len; i++) {
87 intArray[i] = myRandom.nextInt();
88 }
89 // use our own sort algorithm, independent of the host JDK
90 BubbleSort.sort(intArray);
91 }
92
93 /**
94 * Computed the BogoIPS for this host CPU.
95 *
96 * @return
97 */
98 public static double currentBIPS() {
99 return computeBogoIPS(LAST_N);
100 }
101
102 static double min(double a, double b) {
103 return (a <= b) ? a : b;
104 }
105
106 /**
107 * Assertion used for values that <b>decrease</b> with faster CPUs, typically
108 * the time (duration) needed to perform a task.
109 *
110 * @param currentDuration
111 * @param referenceDuration
112 * @param referenceBIPS
113 * @throws AssertionFailedError
114 */
115 public static void assertDuration(double currentDuration, long referenceDuration, double referenceBIPS) throws AssertionFailedError {
116 double ajustedDuration = adjustExpectedDuration(referenceDuration, referenceBIPS);
117 if (currentDuration > ajustedDuration * SLACK_FACTOR) {
118 throw new AssertionFailedError("current duration " + currentDuration + " exceeded expected " + ajustedDuration + " (adjusted reference), "
119 + referenceDuration + " (raw reference)");
120 }
121 }
122
123 /**
124 * Assertion used for values that <b>increase<b> with faster CPUs, typically
125 * the number of operations accomplished per unit of time.
126 *
127 * @param currentPerformance
128 * @param referencePerformance
129 * @param referenceBIPS
130 * @throws AssertionFailedError
131 */
132 public static void assertPerformance(double currentPerformance, long referencePerformance, double referenceBIPS) throws AssertionFailedError {
133 double ajustedPerf = adjustExpectedPerformance(referencePerformance, referenceBIPS);
134 if (currentPerformance * SLACK_FACTOR < ajustedPerf) {
135 throw new AssertionFailedError(currentPerformance + " below expected " + ajustedPerf + " (adjusted), " + referencePerformance + " (raw)");
136 }
137 }
138
139 private static double adjustExpectedPerformance(long referenceDuration, double referenceBIPS) {
140 double currentBIPS = currentBIPS();
141 return referenceDuration * (currentBIPS / referenceBIPS);
142 }
143
144 private static double adjustExpectedDuration(long referenceDuration, double referenceBIPS) {
145 double currentBIPS = currentBIPS();
146 System.out.println("currentBIPS=" + currentBIPS + " BIPS");
147 return referenceDuration * (referenceBIPS / currentBIPS);
148 }
149 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 /**
27 * This class is used internally by BogoPerf, hence the package private
28 * (default) access.
29 *
30 * @author Ceki
31 */
32 class BubbleSort {
33
34 static void sort(int[] a) {
35 int len = a.length;
36 for (int i = 0; i < len - 1; i++) {
37 for (int j = 0; j < len - 1 - i; j++) {
38 if (a[j] > a[j + 1]) {
39 swap(a, j, j + 1);
40 }
41 }
42 }
43 }
44
45 static void swap(int[] a, int i, int j) {
46 int t = a[i];
47 a[i] = a[j];
48 a[j] = t;
49 }
50 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 /**
27 * This class is used internally by BogoPerf, hence the package private
28 * (default) access.
29 *
30 * @author Ceki
31 */
32 class BubbleSort {
33
34 static void sort(int[] a) {
35 int len = a.length;
36 for (int i = 0; i < len - 1; i++) {
37 for (int j = 0; j < len - 1 - i; j++) {
38 if (a[j] > a[j + 1]) {
39 swap(a, j, j + 1);
40 }
41 }
42 }
43 }
44
45 static void swap(int[] a, int i, int j) {
46 int t = a[i];
47 a[i] = a[j];
48 a[j] = t;
49 }
50 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
28
29 import java.util.Arrays;
30 import java.util.Random;
31
32 import org.junit.Test;
33
34 /**
35 * Test that our BubbleSort algorithm is correctly implemented.
36 *
37 * @author Ceki
38 *
39 */
40 public class BubbleSortTest {
41
42 @Test
43 public void testSmoke() {
44 int[] a = new int[] { 5, 3, 2, 7 };
45 BubbleSort.sort(a);
46 int i = 0;
47 assertEquals(2, a[i++]);
48 assertEquals(3, a[i++]);
49 assertEquals(5, a[i++]);
50 assertEquals(7, a[i++]);
51 }
52
53 @Test
54 public void testEmpty() {
55 int[] a = new int[] {};
56 BubbleSort.sort(a);
57 }
58
59 @Test
60 public void testSorted() {
61 int[] a = new int[] { 3, 30, 300, 3000 };
62 BubbleSort.sort(a);
63 int i = 0;
64 assertEquals(3, a[i++]);
65 assertEquals(30, a[i++]);
66 assertEquals(300, a[i++]);
67 assertEquals(3000, a[i++]);
68 }
69
70 @Test
71 public void testInverted() {
72 int[] a = new int[] { 3000, 300, 30, 3 };
73 BubbleSort.sort(a);
74 int i = 0;
75 assertEquals(3, a[i++]);
76 assertEquals(30, a[i++]);
77 assertEquals(300, a[i++]);
78 assertEquals(3000, a[i++]);
79 }
80
81 @Test
82 public void testWithSameEntry() {
83 int[] a = new int[] { 10, 20, 10, 20 };
84 BubbleSort.sort(a);
85 int i = 0;
86 assertEquals(10, a[i++]);
87 assertEquals(10, a[i++]);
88 assertEquals(20, a[i++]);
89 assertEquals(20, a[i++]);
90 }
91
92 @Test
93 public void testRandom() {
94 int len = 100;
95 Random random = new Random(156);
96 int[] a = new int[len];
97 int[] witness = new int[len];
98 for (int i = 0; i < len; i++) {
99 int r = random.nextInt();
100 a[i] = r;
101 witness[i] = r;
102 }
103 BubbleSort.sort(a);
104 Arrays.sort(witness);
105 assertTrue(Arrays.equals(witness, a));
106 }
107
108 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
28
29 import java.util.Arrays;
30 import java.util.Random;
31
32 import org.junit.Test;
33
34 /**
35 * Test that our BubbleSort algorithm is correctly implemented.
36 *
37 * @author Ceki
38 *
39 */
40 public class BubbleSortTest {
41
42 @Test
43 public void testSmoke() {
44 int[] a = new int[] { 5, 3, 2, 7 };
45 BubbleSort.sort(a);
46 int i = 0;
47 assertEquals(2, a[i++]);
48 assertEquals(3, a[i++]);
49 assertEquals(5, a[i++]);
50 assertEquals(7, a[i++]);
51 }
52
53 @Test
54 public void testEmpty() {
55 int[] a = new int[] {};
56 BubbleSort.sort(a);
57 }
58
59 @Test
60 public void testSorted() {
61 int[] a = new int[] { 3, 30, 300, 3000 };
62 BubbleSort.sort(a);
63 int i = 0;
64 assertEquals(3, a[i++]);
65 assertEquals(30, a[i++]);
66 assertEquals(300, a[i++]);
67 assertEquals(3000, a[i++]);
68 }
69
70 @Test
71 public void testInverted() {
72 int[] a = new int[] { 3000, 300, 30, 3 };
73 BubbleSort.sort(a);
74 int i = 0;
75 assertEquals(3, a[i++]);
76 assertEquals(30, a[i++]);
77 assertEquals(300, a[i++]);
78 assertEquals(3000, a[i++]);
79 }
80
81 @Test
82 public void testWithSameEntry() {
83 int[] a = new int[] { 10, 20, 10, 20 };
84 BubbleSort.sort(a);
85 int i = 0;
86 assertEquals(10, a[i++]);
87 assertEquals(10, a[i++]);
88 assertEquals(20, a[i++]);
89 assertEquals(20, a[i++]);
90 }
91
92 @Test
93 public void testRandom() {
94 int len = 100;
95 Random random = new Random(156);
96 int[] a = new int[len];
97 int[] witness = new int[len];
98 for (int i = 0; i < len; i++) {
99 int r = random.nextInt();
100 a[i] = r;
101 witness[i] = r;
102 }
103 BubbleSort.sort(a);
104 Arrays.sort(witness);
105 assertTrue(Arrays.equals(witness, a));
106 }
107
108 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.text.MessageFormat;
27
28 import org.junit.Ignore;
29 import org.junit.Test;
30
31 @Ignore
32 public class MessageFormatterPerfTest { // extends TestCase {
33
34 Integer i1 = new Integer(1);
35 Integer i2 = new Integer(2);
36 static long RUN_LENGTH = 100 * 1000;
37 //
38 static long REFERENCE_BIPS = 48416;
39
40 public void XtestJDKFormatterPerf() {
41 jdkMessageFormatter(RUN_LENGTH);
42 double duration = jdkMessageFormatter(RUN_LENGTH);
43 System.out.println("jdk duration = " + duration + " nanos");
44 }
45
46 @Test
47 public void testSLF4JPerf_OneArg() {
48 slf4jMessageFormatter_OneArg(RUN_LENGTH);
49 double duration = slf4jMessageFormatter_OneArg(RUN_LENGTH);
50 System.out.println("duration=" + duration);
51 long referencePerf = 36;
52 BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS);
53 }
54
55 @Test
56 public void testSLF4JPerf_TwoArg() {
57 slf4jMessageFormatter_TwoArg(RUN_LENGTH);
58 double duration = slf4jMessageFormatter_TwoArg(RUN_LENGTH);
59 long referencePerf = 60;
60 BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS);
61 }
62
63 public double slf4jMessageFormatter_OneArg(long len) {
64 long start = System.nanoTime();
65 for (int i = 0; i < len; i++) {
66 final FormattingTuple tp = MessageFormatter.format("This is some rather short message {} ", i1);
67 tp.getMessage();
68 tp.getArgArray();
69 tp.getThrowable();
70
71 MessageFormatter.format("This is some rather short message {} ", i1);
72 }
73 long end = System.nanoTime();
74 return (end - start) / (1000 * 1000.0);
75 }
76
77 public double slf4jMessageFormatter_TwoArg(long len) {
78 long start = System.nanoTime();
79 for (int i = 0; i < len; i++) {
80 final FormattingTuple tp = MessageFormatter.format("This is some {} short message {} ", i1, i2);
81 tp.getMessage();
82 tp.getArgArray();
83 tp.getThrowable();
84 }
85 long end = System.nanoTime();
86 return (end - start) / (1000 * 1000.0);
87 }
88
89 public double jdkMessageFormatter(long len) {
90 @SuppressWarnings("unused")
91 String s = "";
92 s += ""; // keep compiler happy
93 long start = System.currentTimeMillis();
94 Object[] oa = new Object[] { i1 };
95 for (int i = 0; i < len; i++) {
96 s = MessageFormat.format("This is some rather short message {0}", oa);
97 }
98 long end = System.currentTimeMillis();
99 return (1.0 * end - start);
100 }
101
102 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.text.MessageFormat;
27
28 import org.junit.Ignore;
29 import org.junit.Test;
30
31 @Ignore
32 public class MessageFormatterPerfTest { // extends TestCase {
33
34 Integer i1 = new Integer(1);
35 Integer i2 = new Integer(2);
36 static long RUN_LENGTH = 100 * 1000;
37 //
38 static long REFERENCE_BIPS = 48416;
39
40 public void XtestJDKFormatterPerf() {
41 jdkMessageFormatter(RUN_LENGTH);
42 double duration = jdkMessageFormatter(RUN_LENGTH);
43 System.out.println("jdk duration = " + duration + " nanos");
44 }
45
46 @Test
47 public void testSLF4JPerf_OneArg() {
48 slf4jMessageFormatter_OneArg(RUN_LENGTH);
49 double duration = slf4jMessageFormatter_OneArg(RUN_LENGTH);
50 System.out.println("duration=" + duration);
51 long referencePerf = 36;
52 BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS);
53 }
54
55 @Test
56 public void testSLF4JPerf_TwoArg() {
57 slf4jMessageFormatter_TwoArg(RUN_LENGTH);
58 double duration = slf4jMessageFormatter_TwoArg(RUN_LENGTH);
59 long referencePerf = 60;
60 BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS);
61 }
62
63 public double slf4jMessageFormatter_OneArg(long len) {
64 long start = System.nanoTime();
65 for (int i = 0; i < len; i++) {
66 final FormattingTuple tp = MessageFormatter.format("This is some rather short message {} ", i1);
67 tp.getMessage();
68 tp.getArgArray();
69 tp.getThrowable();
70
71 MessageFormatter.format("This is some rather short message {} ", i1);
72 }
73 long end = System.nanoTime();
74 return (end - start) / (1000 * 1000.0);
75 }
76
77 public double slf4jMessageFormatter_TwoArg(long len) {
78 long start = System.nanoTime();
79 for (int i = 0; i < len; i++) {
80 final FormattingTuple tp = MessageFormatter.format("This is some {} short message {} ", i1, i2);
81 tp.getMessage();
82 tp.getArgArray();
83 tp.getThrowable();
84 }
85 long end = System.nanoTime();
86 return (end - start) / (1000 * 1000.0);
87 }
88
89 public double jdkMessageFormatter(long len) {
90 @SuppressWarnings("unused")
91 String s = "";
92 s += ""; // keep compiler happy
93 long start = System.currentTimeMillis();
94 Object[] oa = new Object[] { i1 };
95 for (int i = 0; i < len; i++) {
96 s = MessageFormat.format("This is some rather short message {0}", oa);
97 }
98 long end = System.currentTimeMillis();
99 return (1.0 * end - start);
100 }
101
102 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.Arrays;
27
28 import org.junit.Test;
29
30 import static org.junit.Assert.*;
31
32 /**
33 * @author Ceki Gulcu
34 */
35 public class MessageFormatterTest {
36
37 Integer i1 = new Integer(1);
38 Integer i2 = new Integer(2);
39 Integer i3 = new Integer(3);
40 Integer[] ia0 = new Integer[] { i1, i2, i3 };
41 Integer[] ia1 = new Integer[] { new Integer(10), new Integer(20), new Integer(30) };
42
43 String result;
44
45 @Test
46 public void testNull() {
47 result = MessageFormatter.format(null, i1).getMessage();
48 assertEquals(null, result);
49 }
50
51 @Test
52 public void nullParametersShouldBeHandledWithoutBarfing() {
53 result = MessageFormatter.format("Value is {}.", null).getMessage();
54 assertEquals("Value is null.", result);
55
56 result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, null).getMessage();
57 assertEquals("Val1 is null, val2 is null.", result);
58
59 result = MessageFormatter.format("Val1 is {}, val2 is {}.", i1, null).getMessage();
60 assertEquals("Val1 is 1, val2 is null.", result);
61
62 result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, i2).getMessage();
63 assertEquals("Val1 is null, val2 is 2.", result);
64
65 result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, null }).getMessage();
66 assertEquals("Val1 is null, val2 is null, val3 is null", result);
67
68 result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, i2, i3 }).getMessage();
69 assertEquals("Val1 is null, val2 is 2, val3 is 3", result);
70
71 result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, i3 }).getMessage();
72 assertEquals("Val1 is null, val2 is null, val3 is 3", result);
73 }
74
75 @Test
76 public void verifyOneParameterIsHandledCorrectly() {
77 result = MessageFormatter.format("Value is {}.", i3).getMessage();
78 assertEquals("Value is 3.", result);
79
80 result = MessageFormatter.format("Value is {", i3).getMessage();
81 assertEquals("Value is {", result);
82
83 result = MessageFormatter.format("{} is larger than 2.", i3).getMessage();
84 assertEquals("3 is larger than 2.", result);
85
86 result = MessageFormatter.format("No subst", i3).getMessage();
87 assertEquals("No subst", result);
88
89 result = MessageFormatter.format("Incorrect {subst", i3).getMessage();
90 assertEquals("Incorrect {subst", result);
91
92 result = MessageFormatter.format("Value is {bla} {}", i3).getMessage();
93 assertEquals("Value is {bla} 3", result);
94
95 result = MessageFormatter.format("Escaped \\{} subst", i3).getMessage();
96 assertEquals("Escaped {} subst", result);
97
98 result = MessageFormatter.format("{Escaped", i3).getMessage();
99 assertEquals("{Escaped", result);
100
101 result = MessageFormatter.format("\\{}Escaped", i3).getMessage();
102 assertEquals("{}Escaped", result);
103
104 result = MessageFormatter.format("File name is {{}}.", "App folder.zip").getMessage();
105 assertEquals("File name is {App folder.zip}.", result);
106
107 // escaping the escape character
108 result = MessageFormatter.format("File name is C:\\\\{}.", "App folder.zip").getMessage();
109 assertEquals("File name is C:\\App folder.zip.", result);
110 }
111
112 @Test
113 public void testTwoParameters() {
114 result = MessageFormatter.format("Value {} is smaller than {}.", i1, i2).getMessage();
115 assertEquals("Value 1 is smaller than 2.", result);
116
117 result = MessageFormatter.format("Value {} is smaller than {}", i1, i2).getMessage();
118 assertEquals("Value 1 is smaller than 2", result);
119
120 result = MessageFormatter.format("{}{}", i1, i2).getMessage();
121 assertEquals("12", result);
122
123 result = MessageFormatter.format("Val1={}, Val2={", i1, i2).getMessage();
124 assertEquals("Val1=1, Val2={", result);
125
126 result = MessageFormatter.format("Value {} is smaller than \\{}", i1, i2).getMessage();
127 assertEquals("Value 1 is smaller than {}", result);
128
129 result = MessageFormatter.format("Value {} is smaller than \\{} tail", i1, i2).getMessage();
130 assertEquals("Value 1 is smaller than {} tail", result);
131
132 result = MessageFormatter.format("Value {} is smaller than \\{", i1, i2).getMessage();
133 assertEquals("Value 1 is smaller than \\{", result);
134
135 result = MessageFormatter.format("Value {} is smaller than {tail", i1, i2).getMessage();
136 assertEquals("Value 1 is smaller than {tail", result);
137
138 result = MessageFormatter.format("Value \\{} is smaller than {}", i1, i2).getMessage();
139 assertEquals("Value {} is smaller than 1", result);
140 }
141
142 @Test
143 public void testExceptionIn_toString() {
144 Object o = new Object() {
145 public String toString() {
146 throw new IllegalStateException("a");
147 }
148 };
149 result = MessageFormatter.format("Troublesome object {}", o).getMessage();
150 assertEquals("Troublesome object [FAILED toString()]", result);
151
152 }
153
154 @Test
155 public void testNullArray() {
156 String msg0 = "msg0";
157 String msg1 = "msg1 {}";
158 String msg2 = "msg2 {} {}";
159 String msg3 = "msg3 {} {} {}";
160
161 Object[] args = null;
162
163 result = MessageFormatter.arrayFormat(msg0, args).getMessage();
164 assertEquals(msg0, result);
165
166 result = MessageFormatter.arrayFormat(msg1, args).getMessage();
167 assertEquals(msg1, result);
168
169 result = MessageFormatter.arrayFormat(msg2, args).getMessage();
170 assertEquals(msg2, result);
171
172 result = MessageFormatter.arrayFormat(msg3, args).getMessage();
173 assertEquals(msg3, result);
174 }
175
176 // tests the case when the parameters are supplied in a single array
177 @Test
178 public void testArrayFormat() {
179 result = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia0).getMessage();
180 assertEquals("Value 1 is smaller than 2 and 3.", result);
181
182 result = MessageFormatter.arrayFormat("{}{}{}", ia0).getMessage();
183 assertEquals("123", result);
184
185 result = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia0).getMessage();
186 assertEquals("Value 1 is smaller than 2.", result);
187
188 result = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia0).getMessage();
189 assertEquals("Value 1 is smaller than 2", result);
190
191 result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage();
192 assertEquals("Val=1, {, Val=2", result);
193
194 result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage();
195 assertEquals("Val=1, {, Val=2", result);
196
197 result = MessageFormatter.arrayFormat("Val1={}, Val2={", ia0).getMessage();
198 assertEquals("Val1=1, Val2={", result);
199 }
200
201 @Test
202 public void testArrayValues() {
203 Integer p0 = i1;
204 Integer[] p1 = new Integer[] { i2, i3 };
205
206 result = MessageFormatter.format("{}{}", p0, p1).getMessage();
207 assertEquals("1[2, 3]", result);
208
209 // Integer[]
210 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", p1 }).getMessage();
211 assertEquals("a[2, 3]", result);
212
213 // byte[]
214 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new byte[] { 1, 2 } }).getMessage();
215 assertEquals("a[1, 2]", result);
216
217 // int[]
218 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new int[] { 1, 2 } }).getMessage();
219 assertEquals("a[1, 2]", result);
220
221 // float[]
222 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new float[] { 1, 2 } }).getMessage();
223 assertEquals("a[1.0, 2.0]", result);
224
225 // double[]
226 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new double[] { 1, 2 } }).getMessage();
227 assertEquals("a[1.0, 2.0]", result);
228
229 }
230
231 @Test
232 public void testMultiDimensionalArrayValues() {
233 Integer[][] multiIntegerA = new Integer[][] { ia0, ia1 };
234 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntegerA }).getMessage();
235 assertEquals("a[[1, 2, 3], [10, 20, 30]]", result);
236
237 int[][] multiIntA = new int[][] { { 1, 2 }, { 10, 20 } };
238 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntA }).getMessage();
239 assertEquals("a[[1, 2], [10, 20]]", result);
240
241 float[][] multiFloatA = new float[][] { { 1, 2 }, { 10, 20 } };
242 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiFloatA }).getMessage();
243 assertEquals("a[[1.0, 2.0], [10.0, 20.0]]", result);
244
245 Object[][] multiOA = new Object[][] { ia0, ia1 };
246 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiOA }).getMessage();
247 assertEquals("a[[1, 2, 3], [10, 20, 30]]", result);
248
249 Object[][][] _3DOA = new Object[][][] { multiOA, multiOA };
250 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", _3DOA }).getMessage();
251 assertEquals("a[[[1, 2, 3], [10, 20, 30]], [[1, 2, 3], [10, 20, 30]]]", result);
252 }
253
254 @Test
255 public void testCyclicArrays() {
256 {
257 Object[] cyclicA = new Object[1];
258 cyclicA[0] = cyclicA;
259 assertEquals("[[...]]", MessageFormatter.arrayFormat("{}", cyclicA).getMessage());
260 }
261 {
262 Object[] a = new Object[2];
263 a[0] = i1;
264 Object[] c = new Object[] { i3, a };
265 Object[] b = new Object[] { i2, c };
266 a[1] = b;
267 assertEquals("1[2, [3, [1, [...]]]]", MessageFormatter.arrayFormat("{}{}", a).getMessage());
268 }
269 }
270
271 @Test
272 public void testArrayThrowable() {
273 FormattingTuple ft;
274 Throwable t = new Throwable();
275 Object[] ia = new Object[] { i1, i2, i3, t };
276 Object[] iaWitness = new Object[] { i1, i2, i3 };
277
278 ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia);
279 assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage());
280 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
281 assertEquals(t, ft.getThrowable());
282
283 ft = MessageFormatter.arrayFormat("{}{}{}", ia);
284 assertEquals("123", ft.getMessage());
285 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
286 assertEquals(t, ft.getThrowable());
287
288 ft = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia);
289 assertEquals("Value 1 is smaller than 2.", ft.getMessage());
290 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
291 assertEquals(t, ft.getThrowable());
292
293 ft = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia);
294 assertEquals("Value 1 is smaller than 2", ft.getMessage());
295 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
296 assertEquals(t, ft.getThrowable());
297
298 ft = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia);
299 assertEquals("Val=1, {, Val=2", ft.getMessage());
300 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
301 assertEquals(t, ft.getThrowable());
302
303 ft = MessageFormatter.arrayFormat("Val={}, \\{, Val={}", ia);
304 assertEquals("Val=1, \\{, Val=2", ft.getMessage());
305 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
306 assertEquals(t, ft.getThrowable());
307
308 ft = MessageFormatter.arrayFormat("Val1={}, Val2={", ia);
309 assertEquals("Val1=1, Val2={", ft.getMessage());
310 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
311 assertEquals(t, ft.getThrowable());
312
313 ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia);
314 assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage());
315 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
316 assertEquals(t, ft.getThrowable());
317
318 ft = MessageFormatter.arrayFormat("{}{}{}{}", ia);
319 assertEquals("123{}", ft.getMessage());
320 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
321 assertEquals(t, ft.getThrowable());
322
323 ft = MessageFormatter.arrayFormat("1={}", new Object[] { i1 }, t);
324 assertEquals("1=1", ft.getMessage());
325 assertTrue(Arrays.equals(new Object[] { i1 }, ft.getArgArray()));
326 assertEquals(t, ft.getThrowable());
327
328 }
329 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.Arrays;
27
28 import org.junit.Test;
29
30 import static org.junit.Assert.*;
31
32 /**
33 * @author Ceki Gulcu
34 */
35 public class MessageFormatterTest {
36
37 Integer i1 = new Integer(1);
38 Integer i2 = new Integer(2);
39 Integer i3 = new Integer(3);
40 Integer[] ia0 = new Integer[] { i1, i2, i3 };
41 Integer[] ia1 = new Integer[] { new Integer(10), new Integer(20), new Integer(30) };
42
43 String result;
44
45 @Test
46 public void testNull() {
47 result = MessageFormatter.format(null, i1).getMessage();
48 assertEquals(null, result);
49 }
50
51 @Test
52 public void nullParametersShouldBeHandledWithoutBarfing() {
53 result = MessageFormatter.format("Value is {}.", null).getMessage();
54 assertEquals("Value is null.", result);
55
56 result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, null).getMessage();
57 assertEquals("Val1 is null, val2 is null.", result);
58
59 result = MessageFormatter.format("Val1 is {}, val2 is {}.", i1, null).getMessage();
60 assertEquals("Val1 is 1, val2 is null.", result);
61
62 result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, i2).getMessage();
63 assertEquals("Val1 is null, val2 is 2.", result);
64
65 result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, null }).getMessage();
66 assertEquals("Val1 is null, val2 is null, val3 is null", result);
67
68 result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, i2, i3 }).getMessage();
69 assertEquals("Val1 is null, val2 is 2, val3 is 3", result);
70
71 result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, i3 }).getMessage();
72 assertEquals("Val1 is null, val2 is null, val3 is 3", result);
73 }
74
75 @Test
76 public void verifyOneParameterIsHandledCorrectly() {
77 result = MessageFormatter.format("Value is {}.", i3).getMessage();
78 assertEquals("Value is 3.", result);
79
80 result = MessageFormatter.format("Value is {", i3).getMessage();
81 assertEquals("Value is {", result);
82
83 result = MessageFormatter.format("{} is larger than 2.", i3).getMessage();
84 assertEquals("3 is larger than 2.", result);
85
86 result = MessageFormatter.format("No subst", i3).getMessage();
87 assertEquals("No subst", result);
88
89 result = MessageFormatter.format("Incorrect {subst", i3).getMessage();
90 assertEquals("Incorrect {subst", result);
91
92 result = MessageFormatter.format("Value is {bla} {}", i3).getMessage();
93 assertEquals("Value is {bla} 3", result);
94
95 result = MessageFormatter.format("Escaped \\{} subst", i3).getMessage();
96 assertEquals("Escaped {} subst", result);
97
98 result = MessageFormatter.format("{Escaped", i3).getMessage();
99 assertEquals("{Escaped", result);
100
101 result = MessageFormatter.format("\\{}Escaped", i3).getMessage();
102 assertEquals("{}Escaped", result);
103
104 result = MessageFormatter.format("File name is {{}}.", "App folder.zip").getMessage();
105 assertEquals("File name is {App folder.zip}.", result);
106
107 // escaping the escape character
108 result = MessageFormatter.format("File name is C:\\\\{}.", "App folder.zip").getMessage();
109 assertEquals("File name is C:\\App folder.zip.", result);
110 }
111
112 @Test
113 public void testTwoParameters() {
114 result = MessageFormatter.format("Value {} is smaller than {}.", i1, i2).getMessage();
115 assertEquals("Value 1 is smaller than 2.", result);
116
117 result = MessageFormatter.format("Value {} is smaller than {}", i1, i2).getMessage();
118 assertEquals("Value 1 is smaller than 2", result);
119
120 result = MessageFormatter.format("{}{}", i1, i2).getMessage();
121 assertEquals("12", result);
122
123 result = MessageFormatter.format("Val1={}, Val2={", i1, i2).getMessage();
124 assertEquals("Val1=1, Val2={", result);
125
126 result = MessageFormatter.format("Value {} is smaller than \\{}", i1, i2).getMessage();
127 assertEquals("Value 1 is smaller than {}", result);
128
129 result = MessageFormatter.format("Value {} is smaller than \\{} tail", i1, i2).getMessage();
130 assertEquals("Value 1 is smaller than {} tail", result);
131
132 result = MessageFormatter.format("Value {} is smaller than \\{", i1, i2).getMessage();
133 assertEquals("Value 1 is smaller than \\{", result);
134
135 result = MessageFormatter.format("Value {} is smaller than {tail", i1, i2).getMessage();
136 assertEquals("Value 1 is smaller than {tail", result);
137
138 result = MessageFormatter.format("Value \\{} is smaller than {}", i1, i2).getMessage();
139 assertEquals("Value {} is smaller than 1", result);
140 }
141
142 @Test
143 public void testExceptionIn_toString() {
144 Object o = new Object() {
145 public String toString() {
146 throw new IllegalStateException("a");
147 }
148 };
149 result = MessageFormatter.format("Troublesome object {}", o).getMessage();
150 assertEquals("Troublesome object [FAILED toString()]", result);
151
152 }
153
154 @Test
155 public void testNullArray() {
156 String msg0 = "msg0";
157 String msg1 = "msg1 {}";
158 String msg2 = "msg2 {} {}";
159 String msg3 = "msg3 {} {} {}";
160
161 Object[] args = null;
162
163 result = MessageFormatter.arrayFormat(msg0, args).getMessage();
164 assertEquals(msg0, result);
165
166 result = MessageFormatter.arrayFormat(msg1, args).getMessage();
167 assertEquals(msg1, result);
168
169 result = MessageFormatter.arrayFormat(msg2, args).getMessage();
170 assertEquals(msg2, result);
171
172 result = MessageFormatter.arrayFormat(msg3, args).getMessage();
173 assertEquals(msg3, result);
174 }
175
176 // tests the case when the parameters are supplied in a single array
177 @Test
178 public void testArrayFormat() {
179 result = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia0).getMessage();
180 assertEquals("Value 1 is smaller than 2 and 3.", result);
181
182 result = MessageFormatter.arrayFormat("{}{}{}", ia0).getMessage();
183 assertEquals("123", result);
184
185 result = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia0).getMessage();
186 assertEquals("Value 1 is smaller than 2.", result);
187
188 result = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia0).getMessage();
189 assertEquals("Value 1 is smaller than 2", result);
190
191 result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage();
192 assertEquals("Val=1, {, Val=2", result);
193
194 result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage();
195 assertEquals("Val=1, {, Val=2", result);
196
197 result = MessageFormatter.arrayFormat("Val1={}, Val2={", ia0).getMessage();
198 assertEquals("Val1=1, Val2={", result);
199 }
200
201 @Test
202 public void testArrayValues() {
203 Integer p0 = i1;
204 Integer[] p1 = new Integer[] { i2, i3 };
205
206 result = MessageFormatter.format("{}{}", p0, p1).getMessage();
207 assertEquals("1[2, 3]", result);
208
209 // Integer[]
210 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", p1 }).getMessage();
211 assertEquals("a[2, 3]", result);
212
213 // byte[]
214 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new byte[] { 1, 2 } }).getMessage();
215 assertEquals("a[1, 2]", result);
216
217 // int[]
218 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new int[] { 1, 2 } }).getMessage();
219 assertEquals("a[1, 2]", result);
220
221 // float[]
222 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new float[] { 1, 2 } }).getMessage();
223 assertEquals("a[1.0, 2.0]", result);
224
225 // double[]
226 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new double[] { 1, 2 } }).getMessage();
227 assertEquals("a[1.0, 2.0]", result);
228
229 }
230
231 @Test
232 public void testMultiDimensionalArrayValues() {
233 Integer[][] multiIntegerA = new Integer[][] { ia0, ia1 };
234 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntegerA }).getMessage();
235 assertEquals("a[[1, 2, 3], [10, 20, 30]]", result);
236
237 int[][] multiIntA = new int[][] { { 1, 2 }, { 10, 20 } };
238 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntA }).getMessage();
239 assertEquals("a[[1, 2], [10, 20]]", result);
240
241 float[][] multiFloatA = new float[][] { { 1, 2 }, { 10, 20 } };
242 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiFloatA }).getMessage();
243 assertEquals("a[[1.0, 2.0], [10.0, 20.0]]", result);
244
245 Object[][] multiOA = new Object[][] { ia0, ia1 };
246 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiOA }).getMessage();
247 assertEquals("a[[1, 2, 3], [10, 20, 30]]", result);
248
249 Object[][][] _3DOA = new Object[][][] { multiOA, multiOA };
250 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", _3DOA }).getMessage();
251 assertEquals("a[[[1, 2, 3], [10, 20, 30]], [[1, 2, 3], [10, 20, 30]]]", result);
252 }
253
254 @Test
255 public void testCyclicArrays() {
256 {
257 Object[] cyclicA = new Object[1];
258 cyclicA[0] = cyclicA;
259 assertEquals("[[...]]", MessageFormatter.arrayFormat("{}", cyclicA).getMessage());
260 }
261 {
262 Object[] a = new Object[2];
263 a[0] = i1;
264 Object[] c = new Object[] { i3, a };
265 Object[] b = new Object[] { i2, c };
266 a[1] = b;
267 assertEquals("1[2, [3, [1, [...]]]]", MessageFormatter.arrayFormat("{}{}", a).getMessage());
268 }
269 }
270
271 @Test
272 public void testArrayThrowable() {
273 FormattingTuple ft;
274 Throwable t = new Throwable();
275 Object[] ia = new Object[] { i1, i2, i3, t };
276 Object[] iaWitness = new Object[] { i1, i2, i3 };
277
278 ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia);
279 assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage());
280 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
281 assertEquals(t, ft.getThrowable());
282
283 ft = MessageFormatter.arrayFormat("{}{}{}", ia);
284 assertEquals("123", ft.getMessage());
285 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
286 assertEquals(t, ft.getThrowable());
287
288 ft = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia);
289 assertEquals("Value 1 is smaller than 2.", ft.getMessage());
290 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
291 assertEquals(t, ft.getThrowable());
292
293 ft = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia);
294 assertEquals("Value 1 is smaller than 2", ft.getMessage());
295 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
296 assertEquals(t, ft.getThrowable());
297
298 ft = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia);
299 assertEquals("Val=1, {, Val=2", ft.getMessage());
300 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
301 assertEquals(t, ft.getThrowable());
302
303 ft = MessageFormatter.arrayFormat("Val={}, \\{, Val={}", ia);
304 assertEquals("Val=1, \\{, Val=2", ft.getMessage());
305 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
306 assertEquals(t, ft.getThrowable());
307
308 ft = MessageFormatter.arrayFormat("Val1={}, Val2={", ia);
309 assertEquals("Val1=1, Val2={", ft.getMessage());
310 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
311 assertEquals(t, ft.getThrowable());
312
313 ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia);
314 assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage());
315 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
316 assertEquals(t, ft.getThrowable());
317
318 ft = MessageFormatter.arrayFormat("{}{}{}{}", ia);
319 assertEquals("123{}", ft.getMessage());
320 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
321 assertEquals(t, ft.getThrowable());
322
323 ft = MessageFormatter.arrayFormat("1={}", new Object[] { i1 }, t);
324 assertEquals("1=1", ft.getMessage());
325 assertTrue(Arrays.equals(new Object[] { i1 }, ft.getArgArray()));
326 assertEquals(t, ft.getThrowable());
327
328 }
329 }
0 package org.slf4j.helpers;
1
2 import static org.junit.Assert.assertTrue;
3 import static org.junit.Assert.fail;
4
5 import java.util.ArrayList;
6 import java.util.Collections;
7 import java.util.List;
8 import java.util.Random;
9 import java.util.concurrent.BrokenBarrierException;
10 import java.util.concurrent.CyclicBarrier;
11 import java.util.concurrent.atomic.AtomicLong;
12
13 import org.junit.Test;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerAccessingThread;
16 import org.slf4j.LoggerFactory;
17 import org.slf4j.event.EventRecodingLogger;
18
19 abstract public class MultithreadedInitializationTest {
20 final protected static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2;
21
22 private final List<Logger> createdLoggers = Collections.synchronizedList(new ArrayList<Logger>());
23
24 final private AtomicLong eventCount = new AtomicLong(0);
25 final private CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1);
26
27 int diff = new Random().nextInt(10000);
28
29 @Test
30 public void multiThreadedInitialization() throws InterruptedException, BrokenBarrierException {
31 @SuppressWarnings("unused")
32 LoggerAccessingThread[] accessors = harness();
33
34 Logger logger = LoggerFactory.getLogger(getClass().getName());
35 logger.info("hello");
36 eventCount.getAndIncrement();
37
38 assertAllSubstLoggersAreFixed();
39 long recordedEventCount = getRecordedEventCount();
40 int LENIENCY_COUNT = 16;
41
42 long expectedEventCount = eventCount.get() + extraLogEvents();
43
44 assertTrue(expectedEventCount + " >= " + recordedEventCount, expectedEventCount >= recordedEventCount);
45 assertTrue(expectedEventCount + " < " + recordedEventCount + "+" + LENIENCY_COUNT, expectedEventCount < recordedEventCount + LENIENCY_COUNT);
46 }
47
48 abstract protected long getRecordedEventCount();
49
50 protected int extraLogEvents() {
51 return 0;
52 }
53
54 private void assertAllSubstLoggersAreFixed() {
55 for (Logger logger : createdLoggers) {
56 if (logger instanceof SubstituteLogger) {
57 SubstituteLogger substLogger = (SubstituteLogger) logger;
58 if (substLogger.delegate() instanceof EventRecodingLogger)
59 fail("substLogger " + substLogger.getName() + " has a delegate of type EventRecodingLogger");
60 }
61 }
62 }
63
64 private LoggerAccessingThread[] harness() throws InterruptedException, BrokenBarrierException {
65 LoggerAccessingThread[] threads = new LoggerAccessingThread[THREAD_COUNT];
66 for (int i = 0; i < THREAD_COUNT; i++) {
67 threads[i] = new LoggerAccessingThread(barrier, createdLoggers, i, eventCount);
68 threads[i].start();
69 }
70
71 // trigger barrier
72 barrier.await();
73
74 for (int i = 0; i < THREAD_COUNT; i++) {
75 threads[i].join();
76 }
77
78 return threads;
79 }
80 }
0 package org.slf4j.helpers;
1
2 import static org.junit.Assert.assertTrue;
3 import static org.junit.Assert.fail;
4
5 import java.util.ArrayList;
6 import java.util.Collections;
7 import java.util.List;
8 import java.util.Random;
9 import java.util.concurrent.BrokenBarrierException;
10 import java.util.concurrent.CyclicBarrier;
11 import java.util.concurrent.atomic.AtomicLong;
12
13 import org.junit.Test;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerAccessingThread;
16 import org.slf4j.LoggerFactory;
17 import org.slf4j.event.EventRecodingLogger;
18
19 abstract public class MultithreadedInitializationTest {
20 final protected static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2;
21
22 private final List<Logger> createdLoggers = Collections.synchronizedList(new ArrayList<Logger>());
23
24 final private AtomicLong eventCount = new AtomicLong(0);
25 final private CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1);
26
27 int diff = new Random().nextInt(10000);
28
29 @Test
30 public void multiThreadedInitialization() throws InterruptedException, BrokenBarrierException {
31 @SuppressWarnings("unused")
32 LoggerAccessingThread[] accessors = harness();
33
34 Logger logger = LoggerFactory.getLogger(getClass().getName());
35 logger.info("hello");
36 eventCount.getAndIncrement();
37
38 assertAllSubstLoggersAreFixed();
39 long recordedEventCount = getRecordedEventCount();
40 int LENIENCY_COUNT = 16;
41
42 long expectedEventCount = eventCount.get() + extraLogEvents();
43
44 assertTrue(expectedEventCount + " >= " + recordedEventCount, expectedEventCount >= recordedEventCount);
45 assertTrue(expectedEventCount + " < " + recordedEventCount + "+" + LENIENCY_COUNT, expectedEventCount < recordedEventCount + LENIENCY_COUNT);
46 }
47
48 abstract protected long getRecordedEventCount();
49
50 protected int extraLogEvents() {
51 return 0;
52 }
53
54 private void assertAllSubstLoggersAreFixed() {
55 for (Logger logger : createdLoggers) {
56 if (logger instanceof SubstituteLogger) {
57 SubstituteLogger substLogger = (SubstituteLogger) logger;
58 if (substLogger.delegate() instanceof EventRecodingLogger)
59 fail("substLogger " + substLogger.getName() + " has a delegate of type EventRecodingLogger");
60 }
61 }
62 }
63
64 private LoggerAccessingThread[] harness() throws InterruptedException, BrokenBarrierException {
65 LoggerAccessingThread[] threads = new LoggerAccessingThread[THREAD_COUNT];
66 for (int i = 0; i < THREAD_COUNT; i++) {
67 threads[i] = new LoggerAccessingThread(barrier, createdLoggers, i, eventCount);
68 threads[i].start();
69 }
70
71 // trigger barrier
72 barrier.await();
73
74 for (int i = 0; i < THREAD_COUNT; i++) {
75 threads[i].join();
76 }
77
78 return threads;
79 }
80 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 class MyRandom {
27
28 private final static long m = 200000000041L; // a prime number
29 private final static long a = 2000000011L; // a prime number
30
31 long y;
32 long unused;
33 int bits = 32;
34
35 public MyRandom() {
36 this(System.nanoTime());
37 }
38
39 public MyRandom(long seed) {
40 this.y = seed;
41 }
42
43 int nextInt() {
44 // we don't really care about the randomness of this
45 // generator
46 y = (a * y + 1) % m;
47 unused = y >>> (48 - bits); // just exercise the >>> operator
48 return (int) (y);
49 }
50 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 class MyRandom {
27
28 private final static long m = 200000000041L; // a prime number
29 private final static long a = 2000000011L; // a prime number
30
31 long y;
32 long unused;
33 int bits = 32;
34
35 public MyRandom() {
36 this(System.nanoTime());
37 }
38
39 public MyRandom(long seed) {
40 this.y = seed;
41 }
42
43 int nextInt() {
44 // we don't really care about the randomness of this
45 // generator
46 y = (a * y + 1) % m;
47 unused = y >>> (48 - bits); // just exercise the >>> operator
48 return (int) (y);
49 }
50 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28
29 import java.lang.reflect.InvocationHandler;
30 import java.lang.reflect.InvocationTargetException;
31 import java.lang.reflect.Method;
32 import java.lang.reflect.Proxy;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.HashSet;
36 import java.util.List;
37 import java.util.Set;
38
39 import org.junit.Test;
40 import org.slf4j.Logger;
41 import org.slf4j.event.EventRecodingLogger;
42 import org.slf4j.helpers.SubstituteLogger;
43
44 /**
45 * @author Chetan Mehrotra
46 */
47 public class SubstitutableLoggerTest {
48 private static final Set<String> EXCLUDED_METHODS = new HashSet<String>(Arrays.asList("getName"));
49
50 @Test
51 public void testDelegate() throws Exception {
52 SubstituteLogger log = new SubstituteLogger("foo", null, false);
53 assertTrue(log.delegate() instanceof EventRecodingLogger);
54
55 Set<String> expectedMethodSignatures = determineMethodSignatures(Logger.class);
56 LoggerInvocationHandler ih = new LoggerInvocationHandler();
57 Logger proxyLogger = (Logger) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Logger.class }, ih);
58 log.setDelegate(proxyLogger);
59
60 invokeMethods(log);
61
62 // Assert that all methods are delegated
63 expectedMethodSignatures.removeAll(ih.getInvokedMethodSignatures());
64 if (!expectedMethodSignatures.isEmpty()) {
65 fail("Following methods are not delegated " + expectedMethodSignatures.toString());
66 }
67 }
68
69 private void invokeMethods(Logger proxyLogger) throws InvocationTargetException, IllegalAccessException {
70 for (Method m : Logger.class.getDeclaredMethods()) {
71 if (!EXCLUDED_METHODS.contains(m.getName())) {
72 m.invoke(proxyLogger, new Object[m.getParameterTypes().length]);
73 }
74 }
75 }
76
77 private class LoggerInvocationHandler implements InvocationHandler {
78 private final Set<String> invokedMethodSignatures = new HashSet<String>();
79
80 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
81 invokedMethodSignatures.add(getMethodSignature(method));
82 if (method.getName().startsWith("is")) {
83 return true;
84 }
85 return null;
86 }
87
88 public Set<String> getInvokedMethodSignatures() {
89 return invokedMethodSignatures;
90 }
91 }
92
93 private static Set<String> determineMethodSignatures(Class<Logger> loggerClass) {
94 Set<String> methodSignatures = new HashSet<String>();
95 for (Method m : loggerClass.getDeclaredMethods()) {
96 if (!EXCLUDED_METHODS.contains(m.getName())) {
97 methodSignatures.add(getMethodSignature(m));
98 }
99 }
100 return methodSignatures;
101 }
102
103 private static String getMethodSignature(Method m) {
104 List<String> result = new ArrayList<String>();
105 result.add(m.getName());
106 for (Class<?> clazz : m.getParameterTypes()) {
107 result.add(clazz.getSimpleName());
108 }
109 return result.toString();
110 }
111 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28
29 import java.lang.reflect.InvocationHandler;
30 import java.lang.reflect.InvocationTargetException;
31 import java.lang.reflect.Method;
32 import java.lang.reflect.Proxy;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.HashSet;
36 import java.util.List;
37 import java.util.Set;
38
39 import org.junit.Test;
40 import org.slf4j.Logger;
41 import org.slf4j.event.EventRecodingLogger;
42 import org.slf4j.helpers.SubstituteLogger;
43
44 /**
45 * @author Chetan Mehrotra
46 */
47 public class SubstitutableLoggerTest {
48 private static final Set<String> EXCLUDED_METHODS = new HashSet<String>(Arrays.asList("getName"));
49
50 @Test
51 public void testDelegate() throws Exception {
52 SubstituteLogger log = new SubstituteLogger("foo", null, false);
53 assertTrue(log.delegate() instanceof EventRecodingLogger);
54
55 Set<String> expectedMethodSignatures = determineMethodSignatures(Logger.class);
56 LoggerInvocationHandler ih = new LoggerInvocationHandler();
57 Logger proxyLogger = (Logger) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Logger.class }, ih);
58 log.setDelegate(proxyLogger);
59
60 invokeMethods(log);
61
62 // Assert that all methods are delegated
63 expectedMethodSignatures.removeAll(ih.getInvokedMethodSignatures());
64 if (!expectedMethodSignatures.isEmpty()) {
65 fail("Following methods are not delegated " + expectedMethodSignatures.toString());
66 }
67 }
68
69 private void invokeMethods(Logger proxyLogger) throws InvocationTargetException, IllegalAccessException {
70 for (Method m : Logger.class.getDeclaredMethods()) {
71 if (!EXCLUDED_METHODS.contains(m.getName())) {
72 m.invoke(proxyLogger, new Object[m.getParameterTypes().length]);
73 }
74 }
75 }
76
77 private class LoggerInvocationHandler implements InvocationHandler {
78 private final Set<String> invokedMethodSignatures = new HashSet<String>();
79
80 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
81 invokedMethodSignatures.add(getMethodSignature(method));
82 if (method.getName().startsWith("is")) {
83 return true;
84 }
85 return null;
86 }
87
88 public Set<String> getInvokedMethodSignatures() {
89 return invokedMethodSignatures;
90 }
91 }
92
93 private static Set<String> determineMethodSignatures(Class<Logger> loggerClass) {
94 Set<String> methodSignatures = new HashSet<String>();
95 for (Method m : loggerClass.getDeclaredMethods()) {
96 if (!EXCLUDED_METHODS.contains(m.getName())) {
97 methodSignatures.add(getMethodSignature(m));
98 }
99 }
100 return methodSignatures;
101 }
102
103 private static String getMethodSignature(Method m) {
104 List<String> result = new ArrayList<String>();
105 result.add(m.getName());
106 for (Class<?> clazz : m.getParameterTypes()) {
107 result.add(clazz.getSimpleName());
108 }
109 return result.toString();
110 }
111 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertTrue;
29
30 import org.junit.Test;
31 import org.slf4j.Logger;
32
33 import java.util.Arrays;
34 import java.util.HashSet;
35 import java.util.Set;
36
37 public class SubstituteLoggerFactoryTest {
38 private SubstituteLoggerFactory factory = new SubstituteLoggerFactory();
39
40 @Test
41 public void testFactory() {
42 Logger log = factory.getLogger("foo");
43 assertNotNull(log);
44
45 Logger log2 = factory.getLogger("foo");
46 assertTrue("Loggers with same name must be same", log == log2);
47 }
48
49 @Test
50 public void testLoggerNameList() {
51 factory.getLogger("foo1");
52 factory.getLogger("foo2");
53
54 Set<String> expectedNames = new HashSet<String>(Arrays.asList("foo1", "foo2"));
55 Set<String> actualNames = new HashSet<String>(factory.getLoggerNames());
56
57 assertEquals(expectedNames, actualNames);
58 }
59
60 @Test
61 public void testLoggers() {
62 factory.getLogger("foo1");
63 factory.getLogger("foo2");
64
65 Set<String> expectedNames = new HashSet<String>(Arrays.asList("foo1", "foo2"));
66
67 Set<String> actualNames = new HashSet<String>();
68 for (SubstituteLogger slog : factory.getLoggers()) {
69 actualNames.add(slog.getName());
70 }
71
72 assertEquals(expectedNames, actualNames);
73 }
74
75 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertTrue;
29
30 import org.junit.Test;
31 import org.slf4j.Logger;
32
33 import java.util.Arrays;
34 import java.util.HashSet;
35 import java.util.Set;
36
37 public class SubstituteLoggerFactoryTest {
38 private SubstituteLoggerFactory factory = new SubstituteLoggerFactory();
39
40 @Test
41 public void testFactory() {
42 Logger log = factory.getLogger("foo");
43 assertNotNull(log);
44
45 Logger log2 = factory.getLogger("foo");
46 assertTrue("Loggers with same name must be same", log == log2);
47 }
48
49 @Test
50 public void testLoggerNameList() {
51 factory.getLogger("foo1");
52 factory.getLogger("foo2");
53
54 Set<String> expectedNames = new HashSet<String>(Arrays.asList("foo1", "foo2"));
55 Set<String> actualNames = new HashSet<String>(factory.getLoggerNames());
56
57 assertEquals(expectedNames, actualNames);
58 }
59
60 @Test
61 public void testLoggers() {
62 factory.getLogger("foo1");
63 factory.getLogger("foo2");
64
65 Set<String> expectedNames = new HashSet<String>(Arrays.asList("foo1", "foo2"));
66
67 Set<String> actualNames = new HashSet<String>();
68 for (SubstituteLogger slog : factory.getLoggers()) {
69 actualNames.add(slog.getName());
70 }
71
72 assertEquals(expectedNames, actualNames);
73 }
74
75 }
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>slf4j-ext</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J Extensions Module</name>
16 <description>Extensions to the SLF4J API</description>
17
18 <url>http://www.slf4j.org</url>
19
20 <dependencies>
21 <dependency>
22 <groupId>org.slf4j</groupId>
23 <artifactId>slf4j-api</artifactId>
24 </dependency>
25 <dependency>
26 <groupId>org.slf4j</groupId>
27 <artifactId>slf4j-log4j12</artifactId>
28 <version>${project.version}</version>
29 <scope>test</scope>
30 </dependency>
31 <dependency>
32 <groupId>ch.qos.cal10n</groupId>
33 <artifactId>cal10n-api</artifactId>
34 <optional>true</optional>
35 </dependency>
36 <dependency>
37 <groupId>javassist</groupId>
38 <artifactId>javassist</artifactId>
39 <version>3.4.GA</version>
40 <optional>true</optional>
41 </dependency>
42 <dependency>
43 <groupId>commons-lang</groupId>
44 <artifactId>commons-lang</artifactId>
45 <version>2.4</version>
46 <optional>true</optional>
47 </dependency>
48 </dependencies>
49
50 <build>
51 <plugins>
52 <plugin>
53 <groupId>org.apache.maven.plugins</groupId>
54 <artifactId>maven-surefire-plugin</artifactId>
55 <configuration>
56 <!-- http://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html -->
57 <printSummary>false</printSummary>
58 <forkMode>once</forkMode>
59 <reportFormat>plain</reportFormat>
60 <trimStackTrace>false</trimStackTrace>
61 <excludes>
62 <exclude>**/AllTest.java</exclude>
63 <exclude>**/PackageTest.java</exclude>
64 </excludes>
65 </configuration>
66 </plugin>
67
68 <plugin>
69 <groupId>org.apache.maven.plugins</groupId>
70 <artifactId>maven-jar-plugin</artifactId>
71 <configuration>
72 <archive>
73 <manifestEntries>
74 <Premain-Class>org.slf4j.agent.AgentPremain</Premain-Class>
75 <!-- what is the proper way to specify the maven full name? /ravn -->
76 <Boot-Class-Path>../../../../javassist/javassist/3.4.GA/javassist-3.4.GA.jar javassist-3.4.GA.jar javassist.jar</Boot-Class-Path>
77 </manifestEntries>
78 </archive>
79 </configuration>
80 </plugin>
81 </plugins>
82
83 </build>
84
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>slf4j-ext</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J Extensions Module</name>
16 <description>Extensions to the SLF4J API</description>
17
18 <url>http://www.slf4j.org</url>
19
20 <dependencies>
21 <dependency>
22 <groupId>org.slf4j</groupId>
23 <artifactId>slf4j-api</artifactId>
24 </dependency>
25 <dependency>
26 <groupId>org.slf4j</groupId>
27 <artifactId>slf4j-log4j12</artifactId>
28 <version>${project.version}</version>
29 <scope>test</scope>
30 </dependency>
31 <dependency>
32 <groupId>ch.qos.cal10n</groupId>
33 <artifactId>cal10n-api</artifactId>
34 <optional>true</optional>
35 </dependency>
36 <dependency>
37 <groupId>javassist</groupId>
38 <artifactId>javassist</artifactId>
39 <version>3.4.GA</version>
40 <optional>true</optional>
41 </dependency>
42 <dependency>
43 <groupId>commons-lang</groupId>
44 <artifactId>commons-lang</artifactId>
45 <version>2.4</version>
46 <optional>true</optional>
47 </dependency>
48 </dependencies>
49
50 <build>
51 <plugins>
52 <plugin>
53 <groupId>org.apache.maven.plugins</groupId>
54 <artifactId>maven-surefire-plugin</artifactId>
55 <configuration>
56 <!-- http://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html -->
57 <printSummary>false</printSummary>
58 <forkMode>once</forkMode>
59 <reportFormat>plain</reportFormat>
60 <trimStackTrace>false</trimStackTrace>
61 <excludes>
62 <exclude>**/AllTest.java</exclude>
63 <exclude>**/PackageTest.java</exclude>
64 </excludes>
65 </configuration>
66 </plugin>
67
68 <plugin>
69 <groupId>org.apache.maven.plugins</groupId>
70 <artifactId>maven-jar-plugin</artifactId>
71 <configuration>
72 <archive>
73 <manifestEntries>
74 <Premain-Class>org.slf4j.agent.AgentPremain</Premain-Class>
75 <!-- what is the proper way to specify the maven full name? /ravn -->
76 <Boot-Class-Path>../../../../javassist/javassist/3.4.GA/javassist-3.4.GA.jar javassist-3.4.GA.jar javassist.jar</Boot-Class-Path>
77 </manifestEntries>
78 </archive>
79 </configuration>
80 </plugin>
81 </plugins>
82
83 </build>
84
8585 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import org.slf4j.MDC;
27
28 public class NDC {
29 public final static String PREFIX = "NDC";
30
31 private static int size() {
32 int i = 0;
33 while (true) {
34 String val = MDC.get(PREFIX + i);
35 if (val != null) {
36 i++;
37 } else {
38 break;
39 }
40 }
41 return i;
42 }
43
44 public static void push(String val) {
45 int next = size();
46 MDC.put(PREFIX + next, val);
47 }
48
49 public static String pop() {
50 int next = size();
51 if (next == 0) {
52 return "";
53 }
54 int last = next - 1;
55 String key = PREFIX + last;
56 String val = MDC.get(key);
57 MDC.remove(key);
58 return val;
59 }
60
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import org.slf4j.MDC;
27
28 public class NDC {
29 public final static String PREFIX = "NDC";
30
31 private static int size() {
32 int i = 0;
33 while (true) {
34 String val = MDC.get(PREFIX + i);
35 if (val != null) {
36 i++;
37 } else {
38 break;
39 }
40 }
41 return i;
42 }
43
44 public static void push(String val) {
45 int next = size();
46 MDC.put(PREFIX + next, val);
47 }
48
49 public static String pop() {
50 int next = size();
51 if (next == 0) {
52 return "";
53 }
54 int last = next - 1;
55 String key = PREFIX + last;
56 String val = MDC.get(key);
57 MDC.remove(key);
58 return val;
59 }
60
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.agent;
25
26 /**
27 * <p>
28 * All recognized options in the string passed to the java agent. For
29 * "java -javaagent:foo.jar=OPTIONS HelloWorld" this would be "OPTIONS".
30 * </p>
31 * <p>
32 * It is considered to be a list of options separated by (currently) ";", on the
33 * form "option=value". The interpretation of "value" is specific to each
34 * option.
35 * </p>
36 */
37 public class AgentOptions {
38
39 /**
40 * List of class prefixes to ignore when instrumenting. Note: Classes loaded
41 * before the agent cannot be instrumented.
42 */
43 public static final String IGNORE = "ignore";
44 /**
45 * Indicate the SLF4J level that should be used by the logging statements
46 * added by the agent. Default is "info".
47 */
48 public static final String LEVEL = "level";
49 /**
50 * Indicate that the agent should print out "new java.util.Date()" at the time
51 * the option was processed and at shutdown time (using the shutdown hook).
52 *
53 */
54 public static final String TIME = "time";
55 /**
56 * Indicate that the agent should log actions to System.err, like adding
57 * logging to methods, etc.
58 *
59 */
60 public static final String VERBOSE = "verbose";
61
62 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.agent;
25
26 /**
27 * <p>
28 * All recognized options in the string passed to the java agent. For
29 * "java -javaagent:foo.jar=OPTIONS HelloWorld" this would be "OPTIONS".
30 * </p>
31 * <p>
32 * It is considered to be a list of options separated by (currently) ";", on the
33 * form "option=value". The interpretation of "value" is specific to each
34 * option.
35 * </p>
36 */
37 public class AgentOptions {
38
39 /**
40 * List of class prefixes to ignore when instrumenting. Note: Classes loaded
41 * before the agent cannot be instrumented.
42 */
43 public static final String IGNORE = "ignore";
44 /**
45 * Indicate the SLF4J level that should be used by the logging statements
46 * added by the agent. Default is "info".
47 */
48 public static final String LEVEL = "level";
49 /**
50 * Indicate that the agent should print out "new java.util.Date()" at the time
51 * the option was processed and at shutdown time (using the shutdown hook).
52 *
53 */
54 public static final String TIME = "time";
55 /**
56 * Indicate that the agent should log actions to System.err, like adding
57 * logging to methods, etc.
58 *
59 */
60 public static final String VERBOSE = "verbose";
61
62 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.agent;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.IOException;
28 import java.lang.instrument.Instrumentation;
29 import java.util.Date;
30 import java.util.Properties;
31
32 import org.slf4j.instrumentation.LogTransformer;
33
34 /**
35 * Entry point for slf4j-ext when used as a Java agent.
36 *
37 */
38 public class AgentPremain {
39
40 /**
41 * JavaAgent premain entry point as specified in the MANIFEST.MF file. See
42 * <a href="http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html">http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html</a> for details.
43 *
44 * @param agentArgument
45 * string provided after "=" up to first space
46 * @param instrumentation
47 * instrumentation environment provided by the JVM
48 */
49 public static void premain(String agentArgument, Instrumentation instrumentation) {
50
51 // We cannot do sanity checks for slf4j here as the jars loaded
52 // by the application are not visible here.
53
54 LogTransformer.Builder builder = new LogTransformer.Builder();
55 builder = builder.addEntryExit(true);
56
57 if (agentArgument != null) {
58 Properties args = parseArguments(agentArgument, ",");
59
60 if (args.containsKey(AgentOptions.VERBOSE)) {
61 builder = builder.verbose(true);
62 }
63
64 if (args.containsKey(AgentOptions.TIME)) {
65 printStartStopTimes();
66 }
67
68 if (args.containsKey(AgentOptions.IGNORE)) {
69 String ignore = args.getProperty(AgentOptions.IGNORE);
70 builder = builder.ignore(ignore.split(":"));
71 }
72
73 if (args.containsKey(AgentOptions.LEVEL)) {
74 builder = builder.level(args.getProperty(AgentOptions.LEVEL));
75 }
76 }
77
78 instrumentation.addTransformer(builder.build());
79 }
80
81 /**
82 * Consider the argument string to be a property file (by converting the
83 * splitter character to line feeds), and then reading it like any other
84 * property file.
85 *
86 *
87 * @param agentArgument
88 * string given by instrumentation framework
89 * @param separator
90 * String to convert to line feeds
91 * @return argument converted to properties
92 */
93 private static Properties parseArguments(String agentArgument, String separator) {
94 Properties p = new Properties();
95 try {
96 String argumentAsLines = agentArgument.replaceAll(separator, "\n");
97 p.load(new ByteArrayInputStream(argumentAsLines.getBytes()));
98 } catch (IOException e) {
99 String s = "Could not load arguments as properties";
100 throw new RuntimeException(s, e);
101 }
102 return p;
103 }
104
105 /**
106 * Print the start message to System.err with the time NOW, and register a
107 * shutdown hook which will print the stop message to System.err with the
108 * time then and the number of milliseconds passed since.
109 *
110 */
111 private static void printStartStopTimes() {
112 final long start = System.currentTimeMillis();
113
114 System.err.println("Start at " + new Date());
115
116 Thread hook = new Thread() {
117 @Override
118 public void run() {
119 long timePassed = System.currentTimeMillis() - start;
120 System.err.println("Stop at " + new Date() + ", execution time = " + timePassed + " ms");
121 }
122 };
123 Runtime.getRuntime().addShutdownHook(hook);
124 }
125 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.agent;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.IOException;
28 import java.lang.instrument.Instrumentation;
29 import java.util.Date;
30 import java.util.Properties;
31
32 import org.slf4j.instrumentation.LogTransformer;
33
34 /**
35 * Entry point for slf4j-ext when used as a Java agent.
36 *
37 */
38 public class AgentPremain {
39
40 /**
41 * JavaAgent premain entry point as specified in the MANIFEST.MF file. See
42 * <a href="http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html">http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html</a> for details.
43 *
44 * @param agentArgument
45 * string provided after "=" up to first space
46 * @param instrumentation
47 * instrumentation environment provided by the JVM
48 */
49 public static void premain(String agentArgument, Instrumentation instrumentation) {
50
51 // We cannot do sanity checks for slf4j here as the jars loaded
52 // by the application are not visible here.
53
54 LogTransformer.Builder builder = new LogTransformer.Builder();
55 builder = builder.addEntryExit(true);
56
57 if (agentArgument != null) {
58 Properties args = parseArguments(agentArgument, ",");
59
60 if (args.containsKey(AgentOptions.VERBOSE)) {
61 builder = builder.verbose(true);
62 }
63
64 if (args.containsKey(AgentOptions.TIME)) {
65 printStartStopTimes();
66 }
67
68 if (args.containsKey(AgentOptions.IGNORE)) {
69 String ignore = args.getProperty(AgentOptions.IGNORE);
70 builder = builder.ignore(ignore.split(":"));
71 }
72
73 if (args.containsKey(AgentOptions.LEVEL)) {
74 builder = builder.level(args.getProperty(AgentOptions.LEVEL));
75 }
76 }
77
78 instrumentation.addTransformer(builder.build());
79 }
80
81 /**
82 * Consider the argument string to be a property file (by converting the
83 * splitter character to line feeds), and then reading it like any other
84 * property file.
85 *
86 *
87 * @param agentArgument
88 * string given by instrumentation framework
89 * @param separator
90 * String to convert to line feeds
91 * @return argument converted to properties
92 */
93 private static Properties parseArguments(String agentArgument, String separator) {
94 Properties p = new Properties();
95 try {
96 String argumentAsLines = agentArgument.replaceAll(separator, "\n");
97 p.load(new ByteArrayInputStream(argumentAsLines.getBytes()));
98 } catch (IOException e) {
99 String s = "Could not load arguments as properties";
100 throw new RuntimeException(s, e);
101 }
102 return p;
103 }
104
105 /**
106 * Print the start message to System.err with the time NOW, and register a
107 * shutdown hook which will print the stop message to System.err with the
108 * time then and the number of milliseconds passed since.
109 *
110 */
111 private static void printStartStopTimes() {
112 final long start = System.currentTimeMillis();
113
114 System.err.println("Start at " + new Date());
115
116 Thread hook = new Thread() {
117 @Override
118 public void run() {
119 long timePassed = System.currentTimeMillis() - start;
120 System.err.println("Stop at " + new Date() + ", execution time = " + timePassed + " ms");
121 }
122 };
123 Runtime.getRuntime().addShutdownHook(hook);
124 }
125 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>"-javaagent" routines for SLF4J.</p>
10 <p>The "-javaagent" flag provided in Java 5+ allows for writing
11 agents in Java, which previously was possible in native code only. The
12 full details are available at <a
13 href="http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html">http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html</a>.
14
15
16 Please notice that code made available to the java agent is also
17 available to the actual program executed.</p>
18 <p>The slf4j-ext-X.Y.Z.jar file provides such a java agent, which is
19 implemented in AgentPremain.java. It is used by adding a -javaagent flag to the Java command line:
20
21 E.g.
22 <pre><code>java HelloWorld</code></pre>
23 is changed to
24 <pre><code>java -javaagent:/path/to/slf4j-ext-X.Y.Z.jar=<em>OPTIONS</em> HelloWorld</code></pre>
25
26 What is actually done, depends on the <em>OPTIONS</em> passed to the agent. These are listed in AgentOptions.java.
27 </p>
28
29
30
31 </body>
32 </html>
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>"-javaagent" routines for SLF4J.</p>
10 <p>The "-javaagent" flag provided in Java 5+ allows for writing
11 agents in Java, which previously was possible in native code only. The
12 full details are available at <a
13 href="http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html">http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html</a>.
14
15
16 Please notice that code made available to the java agent is also
17 available to the actual program executed.</p>
18 <p>The slf4j-ext-X.Y.Z.jar file provides such a java agent, which is
19 implemented in AgentPremain.java. It is used by adding a -javaagent flag to the Java command line:
20
21 E.g.
22 <pre><code>java HelloWorld</code></pre>
23 is changed to
24 <pre><code>java -javaagent:/path/to/slf4j-ext-X.Y.Z.jar=<em>OPTIONS</em> HelloWorld</code></pre>
25
26 What is actually done, depends on the <em>OPTIONS</em> passed to the agent. These are listed in AgentOptions.java.
27 </p>
28
29
30
31 </body>
32 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28 import org.slf4j.MarkerFactory;
29 import org.slf4j.ext.LoggerWrapper;
30 import org.slf4j.spi.LocationAwareLogger;
31
32 import ch.qos.cal10n.IMessageConveyor;
33 import ch.qos.cal10n.MessageParameterObj;
34
35 /**
36 * A logger specialized in localized logging. Localization is based in the <a
37 * href="http://cal10n.qos.ch">CAL10N project</p>.
38 *
39 * @author Ceki G&uuml;lc&uuml;
40 */
41 public class LocLogger extends LoggerWrapper implements Logger {
42
43 private static final String FQCN = LocLogger.class.getName();
44
45 /**
46 * Every localized message logged by a LocLogger will bear this marker. It
47 * allows marker-aware implementations to perform additional processing on
48 * localized messages.
49 */
50 static Marker LOCALIZED = MarkerFactory.getMarker("LOCALIZED");
51
52 final IMessageConveyor imc;
53
54 public LocLogger(Logger logger, IMessageConveyor imc) {
55 super(logger, LoggerWrapper.class.getName());
56 if (imc == null) {
57 throw new IllegalArgumentException("IMessageConveyor cannot be null");
58 }
59 this.imc = imc;
60 }
61
62 /**
63 * Log a localized message at the TRACE level.
64 *
65 * @param key
66 * the key used for localization
67 * @param args
68 * optional arguments
69 */
70 public void trace(Enum<?> key, Object... args) {
71 if (!logger.isTraceEnabled()) {
72 return;
73 }
74 String translatedMsg = imc.getMessage(key, args);
75 MessageParameterObj mpo = new MessageParameterObj(key, args);
76
77 if (instanceofLAL) {
78 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.TRACE_INT, translatedMsg, args, null);
79 } else {
80 logger.trace(LOCALIZED, translatedMsg, mpo);
81 }
82 }
83
84 /**
85 * Log a localized message at the DEBUG level.
86 *
87 * @param key
88 * the key used for localization
89 * @param args
90 * optional arguments
91 */
92 public void debug(Enum<?> key, Object... args) {
93 if (!logger.isDebugEnabled()) {
94 return;
95 }
96 String translatedMsg = imc.getMessage(key, args);
97 MessageParameterObj mpo = new MessageParameterObj(key, args);
98
99 if (instanceofLAL) {
100 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.DEBUG_INT, translatedMsg, args, null);
101 } else {
102 logger.debug(LOCALIZED, translatedMsg, mpo);
103 }
104 }
105
106 /**
107 * Log a localized message at the INFO level.
108 *
109 * @param key
110 * the key used for localization
111 * @param args
112 * optional arguments
113 */
114 public void info(Enum<?> key, Object... args) {
115 if (!logger.isInfoEnabled()) {
116 return;
117 }
118 String translatedMsg = imc.getMessage(key, args);
119 MessageParameterObj mpo = new MessageParameterObj(key, args);
120
121 if (instanceofLAL) {
122 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.INFO_INT, translatedMsg, args, null);
123 } else {
124 logger.info(LOCALIZED, translatedMsg, mpo);
125 }
126 }
127
128 /**
129 * Log a localized message at the WARN level.
130 *
131 * @param key
132 * the key used for localization
133 * @param args
134 * optional arguments
135 */
136 public void warn(Enum<?> key, Object... args) {
137 if (!logger.isWarnEnabled()) {
138 return;
139 }
140 String translatedMsg = imc.getMessage(key, args);
141 MessageParameterObj mpo = new MessageParameterObj(key, args);
142
143 if (instanceofLAL) {
144 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.WARN_INT, translatedMsg, args, null);
145 } else {
146 logger.warn(LOCALIZED, translatedMsg, mpo);
147 }
148 }
149
150 /**
151 * Log a localized message at the ERROR level.
152 *
153 * @param key
154 * the key used for localization
155 * @param args
156 * optional arguments
157 */
158 public void error(Enum<?> key, Object... args) {
159 if (!logger.isErrorEnabled()) {
160 return;
161 }
162 String translatedMsg = imc.getMessage(key, args);
163 MessageParameterObj mpo = new MessageParameterObj(key, args);
164
165 if (instanceofLAL) {
166 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.ERROR_INT, translatedMsg, args, null);
167 } else {
168 logger.error(LOCALIZED, translatedMsg, mpo);
169 }
170 }
171
172 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28 import org.slf4j.MarkerFactory;
29 import org.slf4j.ext.LoggerWrapper;
30 import org.slf4j.spi.LocationAwareLogger;
31
32 import ch.qos.cal10n.IMessageConveyor;
33 import ch.qos.cal10n.MessageParameterObj;
34
35 /**
36 * A logger specialized in localized logging. Localization is based in the <a
37 * href="http://cal10n.qos.ch">CAL10N project</p>.
38 *
39 * @author Ceki G&uuml;lc&uuml;
40 */
41 public class LocLogger extends LoggerWrapper implements Logger {
42
43 private static final String FQCN = LocLogger.class.getName();
44
45 /**
46 * Every localized message logged by a LocLogger will bear this marker. It
47 * allows marker-aware implementations to perform additional processing on
48 * localized messages.
49 */
50 static Marker LOCALIZED = MarkerFactory.getMarker("LOCALIZED");
51
52 final IMessageConveyor imc;
53
54 public LocLogger(Logger logger, IMessageConveyor imc) {
55 super(logger, LoggerWrapper.class.getName());
56 if (imc == null) {
57 throw new IllegalArgumentException("IMessageConveyor cannot be null");
58 }
59 this.imc = imc;
60 }
61
62 /**
63 * Log a localized message at the TRACE level.
64 *
65 * @param key
66 * the key used for localization
67 * @param args
68 * optional arguments
69 */
70 public void trace(Enum<?> key, Object... args) {
71 if (!logger.isTraceEnabled()) {
72 return;
73 }
74 String translatedMsg = imc.getMessage(key, args);
75 MessageParameterObj mpo = new MessageParameterObj(key, args);
76
77 if (instanceofLAL) {
78 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.TRACE_INT, translatedMsg, args, null);
79 } else {
80 logger.trace(LOCALIZED, translatedMsg, mpo);
81 }
82 }
83
84 /**
85 * Log a localized message at the DEBUG level.
86 *
87 * @param key
88 * the key used for localization
89 * @param args
90 * optional arguments
91 */
92 public void debug(Enum<?> key, Object... args) {
93 if (!logger.isDebugEnabled()) {
94 return;
95 }
96 String translatedMsg = imc.getMessage(key, args);
97 MessageParameterObj mpo = new MessageParameterObj(key, args);
98
99 if (instanceofLAL) {
100 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.DEBUG_INT, translatedMsg, args, null);
101 } else {
102 logger.debug(LOCALIZED, translatedMsg, mpo);
103 }
104 }
105
106 /**
107 * Log a localized message at the INFO level.
108 *
109 * @param key
110 * the key used for localization
111 * @param args
112 * optional arguments
113 */
114 public void info(Enum<?> key, Object... args) {
115 if (!logger.isInfoEnabled()) {
116 return;
117 }
118 String translatedMsg = imc.getMessage(key, args);
119 MessageParameterObj mpo = new MessageParameterObj(key, args);
120
121 if (instanceofLAL) {
122 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.INFO_INT, translatedMsg, args, null);
123 } else {
124 logger.info(LOCALIZED, translatedMsg, mpo);
125 }
126 }
127
128 /**
129 * Log a localized message at the WARN level.
130 *
131 * @param key
132 * the key used for localization
133 * @param args
134 * optional arguments
135 */
136 public void warn(Enum<?> key, Object... args) {
137 if (!logger.isWarnEnabled()) {
138 return;
139 }
140 String translatedMsg = imc.getMessage(key, args);
141 MessageParameterObj mpo = new MessageParameterObj(key, args);
142
143 if (instanceofLAL) {
144 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.WARN_INT, translatedMsg, args, null);
145 } else {
146 logger.warn(LOCALIZED, translatedMsg, mpo);
147 }
148 }
149
150 /**
151 * Log a localized message at the ERROR level.
152 *
153 * @param key
154 * the key used for localization
155 * @param args
156 * optional arguments
157 */
158 public void error(Enum<?> key, Object... args) {
159 if (!logger.isErrorEnabled()) {
160 return;
161 }
162 String translatedMsg = imc.getMessage(key, args);
163 MessageParameterObj mpo = new MessageParameterObj(key, args);
164
165 if (instanceofLAL) {
166 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.ERROR_INT, translatedMsg, args, null);
167 } else {
168 logger.error(LOCALIZED, translatedMsg, mpo);
169 }
170 }
171
172 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n;
25
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import ch.qos.cal10n.IMessageConveyor;
30
31 /**
32 *
33 * This class is essentially a wrapper around an {@link LoggerFactory} producing
34 * {@link LocLogger} instances.
35 *
36 * <p>
37 * Contrary to {@link LoggerFactory#getLogger(String)} method of
38 * {@link LoggerFactory}, each call to {@link #getLocLogger(String)} produces a new
39 * instance of {@link LocLogger}. This should not matter because a LocLogger
40 * instance does have any state beyond that of the {@link Logger} instance it
41 * wraps and its message conveyor.
42 *
43 * @author Ceki G&uuml;lc&uuml;
44 *
45 */
46 public class LocLoggerFactory {
47
48 final IMessageConveyor imc;
49
50 public LocLoggerFactory(IMessageConveyor imc) {
51 this.imc = imc;
52 }
53
54 /**
55 * Get an LocLogger instance by name.
56 *
57 * @param name
58 * @return LocLogger instance by name.
59 */
60 public LocLogger getLocLogger(String name) {
61 return new LocLogger(LoggerFactory.getLogger(name), imc);
62 }
63
64 /**
65 * Get a new LocLogger instance by class. The returned LocLogger will be named
66 * after the class.
67 *
68 * @param clazz
69 * @return LocLogger instance by class
70 */
71 public LocLogger getLocLogger(Class<?> clazz) {
72 return getLocLogger(clazz.getName());
73 }
74 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n;
25
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import ch.qos.cal10n.IMessageConveyor;
30
31 /**
32 *
33 * This class is essentially a wrapper around an {@link LoggerFactory} producing
34 * {@link LocLogger} instances.
35 *
36 * <p>
37 * Contrary to {@link LoggerFactory#getLogger(String)} method of
38 * {@link LoggerFactory}, each call to {@link #getLocLogger(String)} produces a new
39 * instance of {@link LocLogger}. This should not matter because a LocLogger
40 * instance does have any state beyond that of the {@link Logger} instance it
41 * wraps and its message conveyor.
42 *
43 * @author Ceki G&uuml;lc&uuml;
44 *
45 */
46 public class LocLoggerFactory {
47
48 final IMessageConveyor imc;
49
50 public LocLoggerFactory(IMessageConveyor imc) {
51 this.imc = imc;
52 }
53
54 /**
55 * Get an LocLogger instance by name.
56 *
57 * @param name
58 * @return LocLogger instance by name.
59 */
60 public LocLogger getLocLogger(String name) {
61 return new LocLogger(LoggerFactory.getLogger(name), imc);
62 }
63
64 /**
65 * Get a new LocLogger instance by class. The returned LocLogger will be named
66 * after the class.
67 *
68 * @param clazz
69 * @return LocLogger instance by class
70 */
71 public LocLogger getLocLogger(Class<?> clazz) {
72 return getLocLogger(clazz.getName());
73 }
74 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>SLF4J API extensions</p>
10 </body>
11 </html>
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>SLF4J API extensions</p>
10 </body>
11 </html>
+0
-305
slf4j-ext/src/main/java/org/slf4j/ext/EventData.java less more
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import java.io.Serializable;
27 import java.io.ByteArrayInputStream;
28 import java.io.ByteArrayOutputStream;
29 import java.util.Date;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.Map;
33 import java.beans.XMLDecoder;
34 import java.beans.XMLEncoder;
35 import java.beans.ExceptionListener;
36
37 /**
38 * Base class for Event Data. Event Data contains data to be logged about an
39 * event. Users may extend this class for each EventType they want to log.
40 *
41 * @author Ralph Goers
42 */
43 public class EventData implements Serializable {
44
45 private static final long serialVersionUID = 153270778642103985L;
46
47 private Map<String, Object> eventData = new HashMap<String, Object>();
48 public static final String EVENT_MESSAGE = "EventMessage";
49 public static final String EVENT_TYPE = "EventType";
50 public static final String EVENT_DATETIME = "EventDateTime";
51 public static final String EVENT_ID = "EventId";
52
53 /**
54 * Default Constructor
55 */
56 public EventData() {
57 }
58
59 /**
60 * Constructor to create event data from a Map.
61 *
62 * @param map
63 * The event data.
64 */
65 public EventData(Map<String, Object> map) {
66 eventData.putAll(map);
67 }
68
69 /**
70 * Construct from a serialized form of the Map containing the RequestInfo
71 * elements
72 *
73 * @param xml
74 * The serialized form of the RequestInfo Map.
75 */
76 @SuppressWarnings("unchecked")
77 public EventData(String xml) {
78 ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
79 try {
80 XMLDecoder decoder = new XMLDecoder(bais);
81 this.eventData = (Map<String, Object>) decoder.readObject();
82 } catch (Exception e) {
83 throw new EventException("Error decoding " + xml, e);
84 }
85 }
86
87 /**
88 * Serialize all the EventData items into an XML representation.
89 *
90 * @return an XML String containing all the EventData items.
91 */
92 public String toXML() {
93 return toXML(eventData);
94 }
95
96 /**
97 * Serialize all the EventData items into an XML representation.
98 *
99 * @param map the Map to transform
100 * @return an XML String containing all the EventData items.
101 */
102 public static String toXML(Map<String, Object> map) {
103 ByteArrayOutputStream baos = new ByteArrayOutputStream();
104 try {
105 XMLEncoder encoder = new XMLEncoder(baos);
106 encoder.setExceptionListener(new ExceptionListener() {
107 public void exceptionThrown(Exception exception) {
108 exception.printStackTrace();
109 }
110 });
111 encoder.writeObject(map);
112 encoder.close();
113 return baos.toString();
114 } catch (Exception e) {
115 e.printStackTrace();
116 return null;
117 }
118 }
119
120 /**
121 * Retrieve the event identifier.
122 *
123 * @return The event identifier
124 */
125 public String getEventId() {
126 return (String) this.eventData.get(EVENT_ID);
127 }
128
129 /**
130 * Set the event identifier.
131 *
132 * @param eventId
133 * The event identifier.
134 */
135 public void setEventId(String eventId) {
136 if (eventId == null) {
137 throw new IllegalArgumentException("eventId cannot be null");
138 }
139 this.eventData.put(EVENT_ID, eventId);
140 }
141
142 /**
143 * Retrieve the message text associated with this event, if any.
144 *
145 * @return The message text associated with this event or null if there is
146 * none.
147 */
148 public String getMessage() {
149 return (String) this.eventData.get(EVENT_MESSAGE);
150 }
151
152 /**
153 * Set the message text associated with this event.
154 *
155 * @param message
156 * The message text.
157 */
158 public void setMessage(String message) {
159 this.eventData.put(EVENT_MESSAGE, message);
160 }
161
162 /**
163 * Retrieve the date and time the event occurred.
164 *
165 * @return The Date associated with the event.
166 */
167 public Date getEventDateTime() {
168 return (Date) this.eventData.get(EVENT_DATETIME);
169 }
170
171 /**
172 * Set the date and time the event occurred in case it is not the same as when
173 * the event was logged.
174 *
175 * @param eventDateTime
176 * The event Date.
177 */
178 public void setEventDateTime(Date eventDateTime) {
179 this.eventData.put(EVENT_DATETIME, eventDateTime);
180 }
181
182 /**
183 * Set the type of event that occurred.
184 *
185 * @param eventType
186 * The type of the event.
187 */
188 public void setEventType(String eventType) {
189 this.eventData.put(EVENT_TYPE, eventType);
190 }
191
192 /**
193 * Retrieve the type of the event.
194 *
195 * @return The event type.
196 */
197 public String getEventType() {
198 return (String) this.eventData.get(EVENT_TYPE);
199 }
200
201 /**
202 * Add arbitrary attributes about the event.
203 *
204 * @param name
205 * The attribute's key.
206 * @param obj
207 * The data associated with the key.
208 */
209 public void put(String name, Serializable obj) {
210 this.eventData.put(name, obj);
211 }
212
213 /**
214 * Retrieve an event attribute.
215 *
216 * @param name
217 * The attribute's key.
218 * @return The value associated with the key or null if the key is not
219 * present.
220 */
221 public Serializable get(String name) {
222 return (Serializable) this.eventData.get(name);
223 }
224
225 /**
226 * Populate the event data from a Map.
227 *
228 * @param data
229 * The Map to copy.
230 */
231 public void putAll(Map<String, Object> data) {
232 this.eventData.putAll(data);
233 }
234
235 /**
236 * Returns the number of attributes in the EventData.
237 *
238 * @return the number of attributes in the EventData.
239 */
240 public int getSize() {
241 return this.eventData.size();
242 }
243
244 /**
245 * Returns an Iterator over all the entries in the EventData.
246 *
247 * @return an Iterator that can be used to access all the event attributes.
248 */
249 public Iterator<Map.Entry<String, Object>> getEntrySetIterator() {
250 return this.eventData.entrySet().iterator();
251 }
252
253 /**
254 * Retrieve all the attributes in the EventData as a Map. Changes to this map
255 * will be reflected in the EventData.
256 *
257 * @return The Map of attributes in this EventData instance.
258 */
259 public Map<String, Object> getEventMap() {
260 return this.eventData;
261 }
262
263 /**
264 * Convert the EventData to a String.
265 *
266 * @return The EventData as a String.
267 */
268 @Override
269 public String toString() {
270 return toXML();
271 }
272
273 /**
274 * Compare two EventData objects for equality.
275 *
276 * @param o
277 * The Object to compare.
278 * @return true if the objects are the same instance or contain all the same
279 * keys and their values.
280 */
281 @SuppressWarnings("unchecked")
282 @Override
283 public boolean equals(Object o) {
284 if (this == o) {
285 return true;
286 }
287 if (!(o instanceof EventData || o instanceof Map)) {
288 return false;
289 }
290 Map<String, Object> map = (o instanceof EventData) ? ((EventData) o).getEventMap() : (Map<String, Object>) o;
291
292 return this.eventData.equals(map);
293 }
294
295 /**
296 * Compute the hashCode for this EventData instance.
297 *
298 * @return The hashcode for this EventData instance.
299 */
300 @Override
301 public int hashCode() {
302 return this.eventData.hashCode();
303 }
304 }
+0
-66
slf4j-ext/src/main/java/org/slf4j/ext/EventException.java less more
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 /**
27 * Exception used to identify issues related to an event that is being logged.
28 */
29 public class EventException extends RuntimeException {
30
31 private static final long serialVersionUID = -22873966112391992L;
32
33 /**
34 * Default constructor.
35 */
36 public EventException() {
37 super();
38 }
39
40 /**
41 * Constructor that allows an exception message.
42 * @param exceptionMessage The exception message.
43 */
44 public EventException(String exceptionMessage) {
45 super(exceptionMessage);
46 }
47
48 /**
49 * Constructor that chains another Exception or Error.
50 * @param originalException The original exception.
51 */
52 public EventException(Throwable originalException) {
53 super(originalException);
54 }
55
56 /**
57 * Constructor that chains another Exception or Error and also allows a message
58 * to be specified.
59 * @param exceptionMessage The exception message.
60 * @param originalException The original exception.
61 */
62 public EventException(String exceptionMessage, Throwable originalException) {
63 super(exceptionMessage, originalException);
64 }
65 }
+0
-64
slf4j-ext/src/main/java/org/slf4j/ext/EventLogger.java less more
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.slf4j.LoggerFactory;
27 import org.slf4j.Marker;
28 import org.slf4j.MarkerFactory;
29 import org.slf4j.spi.LocationAwareLogger;
30
31 /**
32 * Simple Logger used to log events. All events are directed to a logger named "EventLogger"
33 * with a level of INFO and with an Event marker.
34 *
35 * @author Ralph Goers
36 */
37 public class EventLogger {
38
39 private static final String FQCN = EventLogger.class.getName();
40
41 static Marker EVENT_MARKER = MarkerFactory.getMarker("EVENT");
42
43 private static LoggerWrapper eventLogger = new LoggerWrapper(LoggerFactory.getLogger("EventLogger"), FQCN);
44
45 /**
46 * There can only be a single EventLogger.
47 */
48 private EventLogger() {
49 }
50
51 /**
52 * Logs the event.
53 *
54 * @param data The EventData.
55 */
56 public static void logEvent(EventData data) {
57 if (eventLogger.instanceofLAL) {
58 ((LocationAwareLogger) eventLogger.logger).log(EVENT_MARKER, FQCN, LocationAwareLogger.INFO_INT, data.toXML(), new Object[] { data }, null);
59 } else {
60 eventLogger.logger.info(EVENT_MARKER, data.toXML(), data);
61 }
62 }
63 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28 import org.slf4j.helpers.FormattingTuple;
29 import org.slf4j.helpers.MessageFormatter;
30 import org.slf4j.spi.LocationAwareLogger;
31
32 /**
33 * A helper class wrapping an {@link org.slf4j.Logger} instance preserving
34 * location information if the wrapped instance supports it.
35 *
36 * @author Ralph Goers
37 * @author Ceki G&uuml;lc&uuml;
38 */
39 public class LoggerWrapper implements Logger {
40
41 // To ensure consistency between two instances sharing the same name
42 // (homonyms)
43 // a LoggerWrapper should not contain any state beyond
44 // the Logger instance it wraps.
45 // Note that 'instanceofLAL' directly depends on Logger.
46 // fqcn depend on the caller, but its value would not be different
47 // between successive invocations of a factory class
48
49 protected final Logger logger;
50 final String fqcn;
51 // is this logger instance a LocationAwareLogger
52 protected final boolean instanceofLAL;
53
54 public LoggerWrapper(Logger logger, String fqcn) {
55 this.logger = logger;
56 this.fqcn = fqcn;
57 if (logger instanceof LocationAwareLogger) {
58 instanceofLAL = true;
59 } else {
60 instanceofLAL = false;
61 }
62 }
63
64 /**
65 * Delegate to the appropriate method of the underlying logger.
66 */
67 public boolean isTraceEnabled() {
68 return logger.isTraceEnabled();
69 }
70
71 /**
72 * Delegate to the appropriate method of the underlying logger.
73 */
74 public boolean isTraceEnabled(Marker marker) {
75 return logger.isTraceEnabled(marker);
76 }
77
78 /**
79 * Delegate to the appropriate method of the underlying logger.
80 */
81 public void trace(String msg) {
82 if (!logger.isTraceEnabled())
83 return;
84
85 if (instanceofLAL) {
86 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, null);
87 } else {
88 logger.trace(msg);
89 }
90 }
91
92 /**
93 * Delegate to the appropriate method of the underlying logger.
94 */
95 public void trace(String format, Object arg) {
96 if (!logger.isTraceEnabled())
97 return;
98
99 if (instanceofLAL) {
100 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
101 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg }, null);
102 } else {
103 logger.trace(format, arg);
104 }
105 }
106
107 /**
108 * Delegate to the appropriate method of the underlying logger.
109 */
110 public void trace(String format, Object arg1, Object arg2) {
111 if (!logger.isTraceEnabled())
112 return;
113
114 if (instanceofLAL) {
115 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
116 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
117 } else {
118 logger.trace(format, arg1, arg2);
119 }
120 }
121
122 /**
123 * Delegate to the appropriate method of the underlying logger.
124 */
125 public void trace(String format, Object... args) {
126 if (!logger.isTraceEnabled())
127 return;
128
129 if (instanceofLAL) {
130 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
131 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, args, null);
132 } else {
133 logger.trace(format, args);
134 }
135 }
136
137 /**
138 * Delegate to the appropriate method of the underlying logger.
139 */
140 public void trace(String msg, Throwable t) {
141 if (!logger.isTraceEnabled())
142 return;
143
144 if (instanceofLAL) {
145 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, t);
146 } else {
147 logger.trace(msg, t);
148 }
149 }
150
151 /**
152 * Delegate to the appropriate method of the underlying logger.
153 */
154 public void trace(Marker marker, String msg) {
155 if (!logger.isTraceEnabled(marker))
156 return;
157 if (instanceofLAL) {
158 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, msg, null, null);
159 } else {
160 logger.trace(marker, msg);
161 }
162 }
163
164 /**
165 * Delegate to the appropriate method of the underlying logger.
166 */
167 public void trace(Marker marker, String format, Object arg) {
168 if (!logger.isTraceEnabled(marker))
169 return;
170 if (instanceofLAL) {
171 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
172 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg }, null);
173 } else {
174 logger.trace(marker, format, arg);
175 }
176 }
177
178 /**
179 * Delegate to the appropriate method of the underlying logger.
180 */
181 public void trace(Marker marker, String format, Object arg1, Object arg2) {
182 if (!logger.isTraceEnabled(marker))
183 return;
184 if (instanceofLAL) {
185 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
186 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
187 } else {
188 logger.trace(marker, format, arg1, arg2);
189 }
190 }
191
192 /**
193 * Delegate to the appropriate method of the underlying logger.
194 */
195 public void trace(Marker marker, String format, Object... args) {
196 if (!logger.isTraceEnabled(marker))
197 return;
198 if (instanceofLAL) {
199 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
200 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, args, null);
201 } else {
202 logger.trace(marker, format, args);
203 }
204 }
205
206 /**
207 * Delegate to the appropriate method of the underlying logger.
208 */
209 public void trace(Marker marker, String msg, Throwable t) {
210 if (!logger.isTraceEnabled(marker))
211 return;
212 if (instanceofLAL) {
213 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, msg, null, t);
214 } else {
215 logger.trace(marker, msg, t);
216 }
217 }
218
219 /**
220 * Delegate to the appropriate method of the underlying logger.
221 */
222 public boolean isDebugEnabled() {
223 return logger.isDebugEnabled();
224 }
225
226 /**
227 * Delegate to the appropriate method of the underlying logger.
228 */
229 public boolean isDebugEnabled(Marker marker) {
230 return logger.isDebugEnabled(marker);
231 }
232
233 /**
234 * Delegate to the appropriate method of the underlying logger.
235 */
236 public void debug(String msg) {
237 if (!logger.isDebugEnabled())
238 return;
239
240 if (instanceofLAL) {
241 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null);
242 } else {
243 logger.debug(msg);
244 }
245 }
246
247 /**
248 * Delegate to the appropriate method of the underlying logger.
249 */
250 public void debug(String format, Object arg) {
251 if (!logger.isDebugEnabled())
252 return;
253
254 if (instanceofLAL) {
255 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
256 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg }, null);
257 } else {
258 logger.debug(format, arg);
259 }
260 }
261
262 /**
263 * Delegate to the appropriate method of the underlying logger.
264 */
265 public void debug(String format, Object arg1, Object arg2) {
266 if (!logger.isDebugEnabled())
267 return;
268
269 if (instanceofLAL) {
270 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
271 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
272 } else {
273 logger.debug(format, arg1, arg2);
274 }
275 }
276
277 /**
278 * Delegate to the appropriate method of the underlying logger.
279 */
280 public void debug(String format, Object... argArray) {
281 if (!logger.isDebugEnabled())
282 return;
283
284 if (instanceofLAL) {
285 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
286 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), ft.getArgArray(), ft.getThrowable());
287 } else {
288 logger.debug(format, argArray);
289 }
290 }
291
292 /**
293 * Delegate to the appropriate method of the underlying logger.
294 */
295 public void debug(String msg, Throwable t) {
296 if (!logger.isDebugEnabled())
297 return;
298
299 if (instanceofLAL) {
300 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, t);
301 } else {
302 logger.debug(msg, t);
303 }
304 }
305
306 /**
307 * Delegate to the appropriate method of the underlying logger.
308 */
309 public void debug(Marker marker, String msg) {
310 if (!logger.isDebugEnabled(marker))
311 return;
312 if (instanceofLAL) {
313 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null);
314 } else {
315 logger.debug(marker, msg);
316 }
317 }
318
319 /**
320 * Delegate to the appropriate method of the underlying logger.
321 */
322 public void debug(Marker marker, String format, Object arg) {
323 if (!logger.isDebugEnabled(marker))
324 return;
325 if (instanceofLAL) {
326 FormattingTuple ft = MessageFormatter.format(format, arg);
327 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), ft.getArgArray(), ft.getThrowable());
328 } else {
329 logger.debug(marker, format, arg);
330 }
331 }
332
333 /**
334 * Delegate to the appropriate method of the underlying logger.
335 */
336 public void debug(Marker marker, String format, Object arg1, Object arg2) {
337 if (!logger.isDebugEnabled(marker))
338 return;
339 if (instanceofLAL) {
340 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
341 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
342 } else {
343 logger.debug(marker, format, arg1, arg2);
344 }
345 }
346
347 /**
348 * Delegate to the appropriate method of the underlying logger.
349 */
350 public void debug(Marker marker, String format, Object... argArray) {
351 if (!logger.isDebugEnabled(marker))
352 return;
353 if (instanceofLAL) {
354
355 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
356 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), argArray, ft.getThrowable());
357 } else {
358 logger.debug(marker, format, argArray);
359 }
360 }
361
362 /**
363 * Delegate to the appropriate method of the underlying logger.
364 */
365 public void debug(Marker marker, String msg, Throwable t) {
366 if (!logger.isDebugEnabled(marker))
367 return;
368 if (instanceofLAL) {
369 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, t);
370 } else {
371 logger.debug(marker, msg, t);
372 }
373 }
374
375 /**
376 * Delegate to the appropriate method of the underlying logger.
377 */
378 public boolean isInfoEnabled() {
379 return logger.isInfoEnabled();
380 }
381
382 /**
383 * Delegate to the appropriate method of the underlying logger.
384 */
385 public boolean isInfoEnabled(Marker marker) {
386 return logger.isInfoEnabled(marker);
387 }
388
389 /**
390 * Delegate to the appropriate method of the underlying logger.
391 */
392 public void info(String msg) {
393 if (!logger.isInfoEnabled())
394 return;
395
396 if (instanceofLAL) {
397 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, null);
398 } else {
399 logger.info(msg);
400 }
401 }
402
403 /**
404 * Delegate to the appropriate method of the underlying logger.
405 */
406 public void info(String format, Object arg) {
407 if (!logger.isInfoEnabled())
408 return;
409
410 if (instanceofLAL) {
411 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
412 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null);
413 } else {
414 logger.info(format, arg);
415 }
416 }
417
418 /**
419 * Delegate to the appropriate method of the underlying logger.
420 */
421 public void info(String format, Object arg1, Object arg2) {
422 if (!logger.isInfoEnabled())
423 return;
424
425 if (instanceofLAL) {
426 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
427 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
428 } else {
429 logger.info(format, arg1, arg2);
430 }
431 }
432
433 /**
434 * Delegate to the appropriate method of the underlying logger.
435 */
436 public void info(String format, Object... args) {
437 if (!logger.isInfoEnabled())
438 return;
439
440 if (instanceofLAL) {
441 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
442 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, args, null);
443 } else {
444 logger.info(format, args);
445 }
446 }
447
448 /**
449 * Delegate to the appropriate method of the underlying logger.
450 */
451 public void info(String msg, Throwable t) {
452 if (!logger.isInfoEnabled())
453 return;
454
455 if (instanceofLAL) {
456 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, t);
457 } else {
458 logger.info(msg, t);
459 }
460 }
461
462 /**
463 * Delegate to the appropriate method of the underlying logger.
464 */
465 public void info(Marker marker, String msg) {
466 if (!logger.isInfoEnabled(marker))
467 return;
468 if (instanceofLAL) {
469 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, msg, null, null);
470 } else {
471 logger.info(marker, msg);
472 }
473 }
474
475 /**
476 * Delegate to the appropriate method of the underlying logger.
477 */
478 public void info(Marker marker, String format, Object arg) {
479 if (!logger.isInfoEnabled(marker))
480 return;
481 if (instanceofLAL) {
482 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
483 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null);
484 } else {
485 logger.info(marker, format, arg);
486 }
487 }
488
489 /**
490 * Delegate to the appropriate method of the underlying logger.
491 */
492 public void info(Marker marker, String format, Object arg1, Object arg2) {
493 if (!logger.isInfoEnabled(marker))
494 return;
495 if (instanceofLAL) {
496 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
497 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
498 } else {
499 logger.info(marker, format, arg1, arg2);
500 }
501 }
502
503 /**
504 * Delegate to the appropriate method of the underlying logger.
505 */
506 public void info(Marker marker, String format, Object... args) {
507 if (!logger.isInfoEnabled(marker))
508 return;
509 if (instanceofLAL) {
510 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
511 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, args, null);
512 } else {
513 logger.info(marker, format, args);
514 }
515 }
516
517 /**
518 * Delegate to the appropriate method of the underlying logger.
519 */
520 public void info(Marker marker, String msg, Throwable t) {
521 if (!logger.isInfoEnabled(marker))
522 return;
523 if (instanceofLAL) {
524 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, msg, null, t);
525 } else {
526 logger.info(marker, msg, t);
527 }
528 }
529
530 public boolean isWarnEnabled() {
531 return logger.isWarnEnabled();
532 }
533
534 /**
535 * Delegate to the appropriate method of the underlying logger.
536 */
537 public boolean isWarnEnabled(Marker marker) {
538 return logger.isWarnEnabled(marker);
539 }
540
541 /**
542 * Delegate to the appropriate method of the underlying logger.
543 */
544 public void warn(String msg) {
545 if (!logger.isWarnEnabled())
546 return;
547
548 if (instanceofLAL) {
549 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, null);
550 } else {
551 logger.warn(msg);
552 }
553 }
554
555 /**
556 * Delegate to the appropriate method of the underlying logger.
557 */
558 public void warn(String format, Object arg) {
559 if (!logger.isWarnEnabled())
560 return;
561
562 if (instanceofLAL) {
563 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
564 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg }, null);
565 } else {
566 logger.warn(format, arg);
567 }
568 }
569
570 /**
571 * Delegate to the appropriate method of the underlying logger.
572 */
573 public void warn(String format, Object arg1, Object arg2) {
574 if (!logger.isWarnEnabled())
575 return;
576
577 if (instanceofLAL) {
578 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
579 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
580 } else {
581 logger.warn(format, arg1, arg2);
582 }
583 }
584
585 /**
586 * Delegate to the appropriate method of the underlying logger.
587 */
588 public void warn(String format, Object... args) {
589 if (!logger.isWarnEnabled())
590 return;
591
592 if (instanceofLAL) {
593 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
594 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, args, null);
595 } else {
596 logger.warn(format, args);
597 }
598 }
599
600 /**
601 * Delegate to the appropriate method of the underlying logger.
602 */
603 public void warn(String msg, Throwable t) {
604 if (!logger.isWarnEnabled())
605 return;
606
607 if (instanceofLAL) {
608 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, t);
609 } else {
610 logger.warn(msg, t);
611 }
612 }
613
614 /**
615 * Delegate to the appropriate method of the underlying logger.
616 */
617 public void warn(Marker marker, String msg) {
618 if (!logger.isWarnEnabled(marker))
619 return;
620 if (instanceofLAL) {
621 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, msg, null, null);
622 } else {
623 logger.warn(marker, msg);
624 }
625 }
626
627 /**
628 * Delegate to the appropriate method of the underlying logger.
629 */
630 public void warn(Marker marker, String format, Object arg) {
631 if (!logger.isWarnEnabled(marker))
632 return;
633 if (instanceofLAL) {
634 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
635 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg }, null);
636 } else {
637 logger.warn(marker, format, arg);
638 }
639 }
640
641 /**
642 * Delegate to the appropriate method of the underlying logger.
643 */
644 public void warn(Marker marker, String format, Object arg1, Object arg2) {
645 if (!logger.isWarnEnabled(marker))
646 return;
647 if (instanceofLAL) {
648 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
649 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
650 } else {
651 logger.warn(marker, format, arg1, arg2);
652 }
653 }
654
655 /**
656 * Delegate to the appropriate method of the underlying logger.
657 */
658 public void warn(Marker marker, String format, Object... args) {
659 if (!logger.isWarnEnabled(marker))
660 return;
661 if (instanceofLAL) {
662 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
663 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, args, null);
664 } else {
665 logger.warn(marker, format, args);
666 }
667 }
668
669 /**
670 * Delegate to the appropriate method of the underlying logger.
671 */
672 public void warn(Marker marker, String msg, Throwable t) {
673 if (!logger.isWarnEnabled(marker))
674 return;
675 if (instanceofLAL) {
676 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, msg, null, t);
677 } else {
678 logger.warn(marker, msg, t);
679 }
680 }
681
682 /**
683 * Delegate to the appropriate method of the underlying logger.
684 */
685 public boolean isErrorEnabled() {
686 return logger.isErrorEnabled();
687 }
688
689 /**
690 * Delegate to the appropriate method of the underlying logger.
691 */
692 public boolean isErrorEnabled(Marker marker) {
693 return logger.isErrorEnabled(marker);
694 }
695
696 /**
697 * Delegate to the appropriate method of the underlying logger.
698 */
699 public void error(String msg) {
700 if (!logger.isErrorEnabled())
701 return;
702
703 if (instanceofLAL) {
704 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, null);
705 } else {
706 logger.error(msg);
707 }
708 }
709
710 /**
711 * Delegate to the appropriate method of the underlying logger.
712 */
713 public void error(String format, Object arg) {
714 if (!logger.isErrorEnabled())
715 return;
716
717 if (instanceofLAL) {
718 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
719 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg }, null);
720 } else {
721 logger.error(format, arg);
722 }
723 }
724
725 /**
726 * Delegate to the appropriate method of the underlying logger.
727 */
728 public void error(String format, Object arg1, Object arg2) {
729 if (!logger.isErrorEnabled())
730 return;
731
732 if (instanceofLAL) {
733 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
734 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
735 } else {
736 logger.error(format, arg1, arg2);
737 }
738 }
739
740 /**
741 * Delegate to the appropriate method of the underlying logger.
742 */
743 public void error(String format, Object... args) {
744 if (!logger.isErrorEnabled())
745 return;
746
747 if (instanceofLAL) {
748 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
749 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, args, null);
750 } else {
751 logger.error(format, args);
752 }
753 }
754
755 /**
756 * Delegate to the appropriate method of the underlying logger.
757 */
758 public void error(String msg, Throwable t) {
759 if (!logger.isErrorEnabled())
760 return;
761
762 if (instanceofLAL) {
763 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t);
764 } else {
765 logger.error(msg, t);
766 }
767 }
768
769 /**
770 * Delegate to the appropriate method of the underlying logger.
771 */
772 public void error(Marker marker, String msg) {
773 if (!logger.isErrorEnabled(marker))
774 return;
775 if (instanceofLAL) {
776 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, null);
777 } else {
778 logger.error(marker, msg);
779 }
780 }
781
782 /**
783 * Delegate to the appropriate method of the underlying logger.
784 */
785 public void error(Marker marker, String format, Object arg) {
786 if (!logger.isErrorEnabled(marker))
787 return;
788 if (instanceofLAL) {
789 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
790 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg }, null);
791 } else {
792 logger.error(marker, format, arg);
793 }
794 }
795
796 /**
797 * Delegate to the appropriate method of the underlying logger.
798 */
799 public void error(Marker marker, String format, Object arg1, Object arg2) {
800 if (!logger.isErrorEnabled(marker))
801 return;
802 if (instanceofLAL) {
803 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
804 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
805 } else {
806 logger.error(marker, format, arg1, arg2);
807 }
808 }
809
810 /**
811 * Delegate to the appropriate method of the underlying logger.
812 */
813 public void error(Marker marker, String format, Object... args) {
814 if (!logger.isErrorEnabled(marker))
815 return;
816 if (instanceofLAL) {
817 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
818 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, args, null);
819 } else {
820 logger.error(marker, format, args);
821 }
822 }
823
824 /**
825 * Delegate to the appropriate method of the underlying logger.
826 */
827 public void error(Marker marker, String msg, Throwable t) {
828 if (!logger.isErrorEnabled(marker))
829 return;
830 if (instanceofLAL) {
831 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t);
832 } else {
833 logger.error(marker, msg, t);
834 }
835 }
836
837 /**
838 * Delegate to the appropriate method of the underlying logger.
839 */
840 public String getName() {
841 return logger.getName();
842 }
843 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28 import org.slf4j.helpers.FormattingTuple;
29 import org.slf4j.helpers.MessageFormatter;
30 import org.slf4j.spi.LocationAwareLogger;
31
32 /**
33 * A helper class wrapping an {@link org.slf4j.Logger} instance preserving
34 * location information if the wrapped instance supports it.
35 *
36 * @author Ralph Goers
37 * @author Ceki G&uuml;lc&uuml;
38 */
39 public class LoggerWrapper implements Logger {
40
41 // To ensure consistency between two instances sharing the same name
42 // (homonyms)
43 // a LoggerWrapper should not contain any state beyond
44 // the Logger instance it wraps.
45 // Note that 'instanceofLAL' directly depends on Logger.
46 // fqcn depend on the caller, but its value would not be different
47 // between successive invocations of a factory class
48
49 protected final Logger logger;
50 final String fqcn;
51 // is this logger instance a LocationAwareLogger
52 protected final boolean instanceofLAL;
53
54 public LoggerWrapper(Logger logger, String fqcn) {
55 this.logger = logger;
56 this.fqcn = fqcn;
57 if (logger instanceof LocationAwareLogger) {
58 instanceofLAL = true;
59 } else {
60 instanceofLAL = false;
61 }
62 }
63
64 /**
65 * Delegate to the appropriate method of the underlying logger.
66 */
67 public boolean isTraceEnabled() {
68 return logger.isTraceEnabled();
69 }
70
71 /**
72 * Delegate to the appropriate method of the underlying logger.
73 */
74 public boolean isTraceEnabled(Marker marker) {
75 return logger.isTraceEnabled(marker);
76 }
77
78 /**
79 * Delegate to the appropriate method of the underlying logger.
80 */
81 public void trace(String msg) {
82 if (!logger.isTraceEnabled())
83 return;
84
85 if (instanceofLAL) {
86 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, null);
87 } else {
88 logger.trace(msg);
89 }
90 }
91
92 /**
93 * Delegate to the appropriate method of the underlying logger.
94 */
95 public void trace(String format, Object arg) {
96 if (!logger.isTraceEnabled())
97 return;
98
99 if (instanceofLAL) {
100 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
101 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg }, null);
102 } else {
103 logger.trace(format, arg);
104 }
105 }
106
107 /**
108 * Delegate to the appropriate method of the underlying logger.
109 */
110 public void trace(String format, Object arg1, Object arg2) {
111 if (!logger.isTraceEnabled())
112 return;
113
114 if (instanceofLAL) {
115 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
116 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
117 } else {
118 logger.trace(format, arg1, arg2);
119 }
120 }
121
122 /**
123 * Delegate to the appropriate method of the underlying logger.
124 */
125 public void trace(String format, Object... args) {
126 if (!logger.isTraceEnabled())
127 return;
128
129 if (instanceofLAL) {
130 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
131 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, args, null);
132 } else {
133 logger.trace(format, args);
134 }
135 }
136
137 /**
138 * Delegate to the appropriate method of the underlying logger.
139 */
140 public void trace(String msg, Throwable t) {
141 if (!logger.isTraceEnabled())
142 return;
143
144 if (instanceofLAL) {
145 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, t);
146 } else {
147 logger.trace(msg, t);
148 }
149 }
150
151 /**
152 * Delegate to the appropriate method of the underlying logger.
153 */
154 public void trace(Marker marker, String msg) {
155 if (!logger.isTraceEnabled(marker))
156 return;
157 if (instanceofLAL) {
158 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, msg, null, null);
159 } else {
160 logger.trace(marker, msg);
161 }
162 }
163
164 /**
165 * Delegate to the appropriate method of the underlying logger.
166 */
167 public void trace(Marker marker, String format, Object arg) {
168 if (!logger.isTraceEnabled(marker))
169 return;
170 if (instanceofLAL) {
171 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
172 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg }, null);
173 } else {
174 logger.trace(marker, format, arg);
175 }
176 }
177
178 /**
179 * Delegate to the appropriate method of the underlying logger.
180 */
181 public void trace(Marker marker, String format, Object arg1, Object arg2) {
182 if (!logger.isTraceEnabled(marker))
183 return;
184 if (instanceofLAL) {
185 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
186 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
187 } else {
188 logger.trace(marker, format, arg1, arg2);
189 }
190 }
191
192 /**
193 * Delegate to the appropriate method of the underlying logger.
194 */
195 public void trace(Marker marker, String format, Object... args) {
196 if (!logger.isTraceEnabled(marker))
197 return;
198 if (instanceofLAL) {
199 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
200 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, args, null);
201 } else {
202 logger.trace(marker, format, args);
203 }
204 }
205
206 /**
207 * Delegate to the appropriate method of the underlying logger.
208 */
209 public void trace(Marker marker, String msg, Throwable t) {
210 if (!logger.isTraceEnabled(marker))
211 return;
212 if (instanceofLAL) {
213 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, msg, null, t);
214 } else {
215 logger.trace(marker, msg, t);
216 }
217 }
218
219 /**
220 * Delegate to the appropriate method of the underlying logger.
221 */
222 public boolean isDebugEnabled() {
223 return logger.isDebugEnabled();
224 }
225
226 /**
227 * Delegate to the appropriate method of the underlying logger.
228 */
229 public boolean isDebugEnabled(Marker marker) {
230 return logger.isDebugEnabled(marker);
231 }
232
233 /**
234 * Delegate to the appropriate method of the underlying logger.
235 */
236 public void debug(String msg) {
237 if (!logger.isDebugEnabled())
238 return;
239
240 if (instanceofLAL) {
241 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null);
242 } else {
243 logger.debug(msg);
244 }
245 }
246
247 /**
248 * Delegate to the appropriate method of the underlying logger.
249 */
250 public void debug(String format, Object arg) {
251 if (!logger.isDebugEnabled())
252 return;
253
254 if (instanceofLAL) {
255 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
256 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg }, null);
257 } else {
258 logger.debug(format, arg);
259 }
260 }
261
262 /**
263 * Delegate to the appropriate method of the underlying logger.
264 */
265 public void debug(String format, Object arg1, Object arg2) {
266 if (!logger.isDebugEnabled())
267 return;
268
269 if (instanceofLAL) {
270 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
271 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
272 } else {
273 logger.debug(format, arg1, arg2);
274 }
275 }
276
277 /**
278 * Delegate to the appropriate method of the underlying logger.
279 */
280 public void debug(String format, Object... argArray) {
281 if (!logger.isDebugEnabled())
282 return;
283
284 if (instanceofLAL) {
285 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
286 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), ft.getArgArray(), ft.getThrowable());
287 } else {
288 logger.debug(format, argArray);
289 }
290 }
291
292 /**
293 * Delegate to the appropriate method of the underlying logger.
294 */
295 public void debug(String msg, Throwable t) {
296 if (!logger.isDebugEnabled())
297 return;
298
299 if (instanceofLAL) {
300 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, t);
301 } else {
302 logger.debug(msg, t);
303 }
304 }
305
306 /**
307 * Delegate to the appropriate method of the underlying logger.
308 */
309 public void debug(Marker marker, String msg) {
310 if (!logger.isDebugEnabled(marker))
311 return;
312 if (instanceofLAL) {
313 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null);
314 } else {
315 logger.debug(marker, msg);
316 }
317 }
318
319 /**
320 * Delegate to the appropriate method of the underlying logger.
321 */
322 public void debug(Marker marker, String format, Object arg) {
323 if (!logger.isDebugEnabled(marker))
324 return;
325 if (instanceofLAL) {
326 FormattingTuple ft = MessageFormatter.format(format, arg);
327 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), ft.getArgArray(), ft.getThrowable());
328 } else {
329 logger.debug(marker, format, arg);
330 }
331 }
332
333 /**
334 * Delegate to the appropriate method of the underlying logger.
335 */
336 public void debug(Marker marker, String format, Object arg1, Object arg2) {
337 if (!logger.isDebugEnabled(marker))
338 return;
339 if (instanceofLAL) {
340 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
341 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
342 } else {
343 logger.debug(marker, format, arg1, arg2);
344 }
345 }
346
347 /**
348 * Delegate to the appropriate method of the underlying logger.
349 */
350 public void debug(Marker marker, String format, Object... argArray) {
351 if (!logger.isDebugEnabled(marker))
352 return;
353 if (instanceofLAL) {
354
355 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
356 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), argArray, ft.getThrowable());
357 } else {
358 logger.debug(marker, format, argArray);
359 }
360 }
361
362 /**
363 * Delegate to the appropriate method of the underlying logger.
364 */
365 public void debug(Marker marker, String msg, Throwable t) {
366 if (!logger.isDebugEnabled(marker))
367 return;
368 if (instanceofLAL) {
369 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, t);
370 } else {
371 logger.debug(marker, msg, t);
372 }
373 }
374
375 /**
376 * Delegate to the appropriate method of the underlying logger.
377 */
378 public boolean isInfoEnabled() {
379 return logger.isInfoEnabled();
380 }
381
382 /**
383 * Delegate to the appropriate method of the underlying logger.
384 */
385 public boolean isInfoEnabled(Marker marker) {
386 return logger.isInfoEnabled(marker);
387 }
388
389 /**
390 * Delegate to the appropriate method of the underlying logger.
391 */
392 public void info(String msg) {
393 if (!logger.isInfoEnabled())
394 return;
395
396 if (instanceofLAL) {
397 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, null);
398 } else {
399 logger.info(msg);
400 }
401 }
402
403 /**
404 * Delegate to the appropriate method of the underlying logger.
405 */
406 public void info(String format, Object arg) {
407 if (!logger.isInfoEnabled())
408 return;
409
410 if (instanceofLAL) {
411 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
412 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null);
413 } else {
414 logger.info(format, arg);
415 }
416 }
417
418 /**
419 * Delegate to the appropriate method of the underlying logger.
420 */
421 public void info(String format, Object arg1, Object arg2) {
422 if (!logger.isInfoEnabled())
423 return;
424
425 if (instanceofLAL) {
426 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
427 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
428 } else {
429 logger.info(format, arg1, arg2);
430 }
431 }
432
433 /**
434 * Delegate to the appropriate method of the underlying logger.
435 */
436 public void info(String format, Object... args) {
437 if (!logger.isInfoEnabled())
438 return;
439
440 if (instanceofLAL) {
441 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
442 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, args, null);
443 } else {
444 logger.info(format, args);
445 }
446 }
447
448 /**
449 * Delegate to the appropriate method of the underlying logger.
450 */
451 public void info(String msg, Throwable t) {
452 if (!logger.isInfoEnabled())
453 return;
454
455 if (instanceofLAL) {
456 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, t);
457 } else {
458 logger.info(msg, t);
459 }
460 }
461
462 /**
463 * Delegate to the appropriate method of the underlying logger.
464 */
465 public void info(Marker marker, String msg) {
466 if (!logger.isInfoEnabled(marker))
467 return;
468 if (instanceofLAL) {
469 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, msg, null, null);
470 } else {
471 logger.info(marker, msg);
472 }
473 }
474
475 /**
476 * Delegate to the appropriate method of the underlying logger.
477 */
478 public void info(Marker marker, String format, Object arg) {
479 if (!logger.isInfoEnabled(marker))
480 return;
481 if (instanceofLAL) {
482 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
483 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null);
484 } else {
485 logger.info(marker, format, arg);
486 }
487 }
488
489 /**
490 * Delegate to the appropriate method of the underlying logger.
491 */
492 public void info(Marker marker, String format, Object arg1, Object arg2) {
493 if (!logger.isInfoEnabled(marker))
494 return;
495 if (instanceofLAL) {
496 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
497 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
498 } else {
499 logger.info(marker, format, arg1, arg2);
500 }
501 }
502
503 /**
504 * Delegate to the appropriate method of the underlying logger.
505 */
506 public void info(Marker marker, String format, Object... args) {
507 if (!logger.isInfoEnabled(marker))
508 return;
509 if (instanceofLAL) {
510 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
511 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, args, null);
512 } else {
513 logger.info(marker, format, args);
514 }
515 }
516
517 /**
518 * Delegate to the appropriate method of the underlying logger.
519 */
520 public void info(Marker marker, String msg, Throwable t) {
521 if (!logger.isInfoEnabled(marker))
522 return;
523 if (instanceofLAL) {
524 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, msg, null, t);
525 } else {
526 logger.info(marker, msg, t);
527 }
528 }
529
530 public boolean isWarnEnabled() {
531 return logger.isWarnEnabled();
532 }
533
534 /**
535 * Delegate to the appropriate method of the underlying logger.
536 */
537 public boolean isWarnEnabled(Marker marker) {
538 return logger.isWarnEnabled(marker);
539 }
540
541 /**
542 * Delegate to the appropriate method of the underlying logger.
543 */
544 public void warn(String msg) {
545 if (!logger.isWarnEnabled())
546 return;
547
548 if (instanceofLAL) {
549 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, null);
550 } else {
551 logger.warn(msg);
552 }
553 }
554
555 /**
556 * Delegate to the appropriate method of the underlying logger.
557 */
558 public void warn(String format, Object arg) {
559 if (!logger.isWarnEnabled())
560 return;
561
562 if (instanceofLAL) {
563 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
564 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg }, null);
565 } else {
566 logger.warn(format, arg);
567 }
568 }
569
570 /**
571 * Delegate to the appropriate method of the underlying logger.
572 */
573 public void warn(String format, Object arg1, Object arg2) {
574 if (!logger.isWarnEnabled())
575 return;
576
577 if (instanceofLAL) {
578 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
579 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
580 } else {
581 logger.warn(format, arg1, arg2);
582 }
583 }
584
585 /**
586 * Delegate to the appropriate method of the underlying logger.
587 */
588 public void warn(String format, Object... args) {
589 if (!logger.isWarnEnabled())
590 return;
591
592 if (instanceofLAL) {
593 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
594 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, args, null);
595 } else {
596 logger.warn(format, args);
597 }
598 }
599
600 /**
601 * Delegate to the appropriate method of the underlying logger.
602 */
603 public void warn(String msg, Throwable t) {
604 if (!logger.isWarnEnabled())
605 return;
606
607 if (instanceofLAL) {
608 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, t);
609 } else {
610 logger.warn(msg, t);
611 }
612 }
613
614 /**
615 * Delegate to the appropriate method of the underlying logger.
616 */
617 public void warn(Marker marker, String msg) {
618 if (!logger.isWarnEnabled(marker))
619 return;
620 if (instanceofLAL) {
621 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, msg, null, null);
622 } else {
623 logger.warn(marker, msg);
624 }
625 }
626
627 /**
628 * Delegate to the appropriate method of the underlying logger.
629 */
630 public void warn(Marker marker, String format, Object arg) {
631 if (!logger.isWarnEnabled(marker))
632 return;
633 if (instanceofLAL) {
634 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
635 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg }, null);
636 } else {
637 logger.warn(marker, format, arg);
638 }
639 }
640
641 /**
642 * Delegate to the appropriate method of the underlying logger.
643 */
644 public void warn(Marker marker, String format, Object arg1, Object arg2) {
645 if (!logger.isWarnEnabled(marker))
646 return;
647 if (instanceofLAL) {
648 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
649 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
650 } else {
651 logger.warn(marker, format, arg1, arg2);
652 }
653 }
654
655 /**
656 * Delegate to the appropriate method of the underlying logger.
657 */
658 public void warn(Marker marker, String format, Object... args) {
659 if (!logger.isWarnEnabled(marker))
660 return;
661 if (instanceofLAL) {
662 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
663 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, args, null);
664 } else {
665 logger.warn(marker, format, args);
666 }
667 }
668
669 /**
670 * Delegate to the appropriate method of the underlying logger.
671 */
672 public void warn(Marker marker, String msg, Throwable t) {
673 if (!logger.isWarnEnabled(marker))
674 return;
675 if (instanceofLAL) {
676 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, msg, null, t);
677 } else {
678 logger.warn(marker, msg, t);
679 }
680 }
681
682 /**
683 * Delegate to the appropriate method of the underlying logger.
684 */
685 public boolean isErrorEnabled() {
686 return logger.isErrorEnabled();
687 }
688
689 /**
690 * Delegate to the appropriate method of the underlying logger.
691 */
692 public boolean isErrorEnabled(Marker marker) {
693 return logger.isErrorEnabled(marker);
694 }
695
696 /**
697 * Delegate to the appropriate method of the underlying logger.
698 */
699 public void error(String msg) {
700 if (!logger.isErrorEnabled())
701 return;
702
703 if (instanceofLAL) {
704 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, null);
705 } else {
706 logger.error(msg);
707 }
708 }
709
710 /**
711 * Delegate to the appropriate method of the underlying logger.
712 */
713 public void error(String format, Object arg) {
714 if (!logger.isErrorEnabled())
715 return;
716
717 if (instanceofLAL) {
718 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
719 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg }, null);
720 } else {
721 logger.error(format, arg);
722 }
723 }
724
725 /**
726 * Delegate to the appropriate method of the underlying logger.
727 */
728 public void error(String format, Object arg1, Object arg2) {
729 if (!logger.isErrorEnabled())
730 return;
731
732 if (instanceofLAL) {
733 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
734 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
735 } else {
736 logger.error(format, arg1, arg2);
737 }
738 }
739
740 /**
741 * Delegate to the appropriate method of the underlying logger.
742 */
743 public void error(String format, Object... args) {
744 if (!logger.isErrorEnabled())
745 return;
746
747 if (instanceofLAL) {
748 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
749 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, args, null);
750 } else {
751 logger.error(format, args);
752 }
753 }
754
755 /**
756 * Delegate to the appropriate method of the underlying logger.
757 */
758 public void error(String msg, Throwable t) {
759 if (!logger.isErrorEnabled())
760 return;
761
762 if (instanceofLAL) {
763 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t);
764 } else {
765 logger.error(msg, t);
766 }
767 }
768
769 /**
770 * Delegate to the appropriate method of the underlying logger.
771 */
772 public void error(Marker marker, String msg) {
773 if (!logger.isErrorEnabled(marker))
774 return;
775 if (instanceofLAL) {
776 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, null);
777 } else {
778 logger.error(marker, msg);
779 }
780 }
781
782 /**
783 * Delegate to the appropriate method of the underlying logger.
784 */
785 public void error(Marker marker, String format, Object arg) {
786 if (!logger.isErrorEnabled(marker))
787 return;
788 if (instanceofLAL) {
789 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
790 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg }, null);
791 } else {
792 logger.error(marker, format, arg);
793 }
794 }
795
796 /**
797 * Delegate to the appropriate method of the underlying logger.
798 */
799 public void error(Marker marker, String format, Object arg1, Object arg2) {
800 if (!logger.isErrorEnabled(marker))
801 return;
802 if (instanceofLAL) {
803 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
804 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
805 } else {
806 logger.error(marker, format, arg1, arg2);
807 }
808 }
809
810 /**
811 * Delegate to the appropriate method of the underlying logger.
812 */
813 public void error(Marker marker, String format, Object... args) {
814 if (!logger.isErrorEnabled(marker))
815 return;
816 if (instanceofLAL) {
817 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
818 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, args, null);
819 } else {
820 logger.error(marker, format, args);
821 }
822 }
823
824 /**
825 * Delegate to the appropriate method of the underlying logger.
826 */
827 public void error(Marker marker, String msg, Throwable t) {
828 if (!logger.isErrorEnabled(marker))
829 return;
830 if (instanceofLAL) {
831 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t);
832 } else {
833 logger.error(marker, msg, t);
834 }
835 }
836
837 /**
838 * Delegate to the appropriate method of the underlying logger.
839 */
840 public String getName() {
841 return logger.getName();
842 }
843 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.apache.commons.lang.text.StrLookup;
27 import org.slf4j.MDC;
28
29 /**
30 * This class can be used with the Commons Lang StrSubstitutor to replace
31 * tokens that occur in Strings with their values in the MDC.
32 *
33 * @author Ralph Goers
34 */
35 public class MDCStrLookup extends StrLookup {
36 /**
37 * Looks up up a value in the MDC.
38 *
39 * @param key the key to be looked up, may be null
40 * @return the matching value, null if no match
41 */
42 public String lookup(String key) {
43 if (key == null) {
44 return null;
45 }
46 return MDC.get(key);
47 }
48 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.apache.commons.lang.text.StrLookup;
27 import org.slf4j.MDC;
28
29 /**
30 * This class can be used with the Commons Lang StrSubstitutor to replace
31 * tokens that occur in Strings with their values in the MDC.
32 *
33 * @author Ralph Goers
34 */
35 public class MDCStrLookup extends StrLookup {
36 /**
37 * Looks up up a value in the MDC.
38 *
39 * @param key the key to be looked up, may be null
40 * @return the matching value, null if no match
41 */
42 public String lookup(String key) {
43 if (key == null) {
44 return null;
45 }
46 return MDC.get(key);
47 }
48 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28 import org.slf4j.MarkerFactory;
29 import org.slf4j.helpers.FormattingTuple;
30 import org.slf4j.helpers.MessageFormatter;
31 import org.slf4j.spi.LocationAwareLogger;
32
33 /**
34 * A utility that provides standard mechanisms for logging certain kinds of
35 * activities.
36 *
37 * @author Ralph Goers
38 * @author Ceki G&uuml;lc&uuml;
39 */
40 public class XLogger extends LoggerWrapper implements Logger {
41
42 private static final String FQCN = XLogger.class.getName();
43 static Marker FLOW_MARKER = MarkerFactory.getMarker("FLOW");
44 static Marker ENTRY_MARKER = MarkerFactory.getMarker("ENTRY");
45 static Marker EXIT_MARKER = MarkerFactory.getMarker("EXIT");
46
47 static Marker EXCEPTION_MARKER = MarkerFactory.getMarker("EXCEPTION");
48 static Marker THROWING_MARKER = MarkerFactory.getMarker("THROWING");
49 static Marker CATCHING_MARKER = MarkerFactory.getMarker("CATCHING");
50
51 static String EXIT_MESSAGE_0 = "exit";
52 static String EXIT_MESSAGE_1 = "exit with ({})";
53
54 static String ENTRY_MESSAGE_0 = "entry";
55 static String ENTRY_MESSAGE_1 = "entry with ({})";
56 static String ENTRY_MESSAGE_2 = "entry with ({}, {})";
57 static String ENTRY_MESSAGE_3 = "entry with ({}, {}, {})";
58 static String ENTRY_MESSAGE_4 = "entry with ({}, {}, {}, {})";
59 static int ENTRY_MESSAGE_ARRAY_LEN = 5;
60 static String[] ENTRY_MESSAGE_ARRAY = new String[ENTRY_MESSAGE_ARRAY_LEN];
61 static {
62 ENTRY_MARKER.add(FLOW_MARKER);
63 EXIT_MARKER.add(FLOW_MARKER);
64 THROWING_MARKER.add(EXCEPTION_MARKER);
65 CATCHING_MARKER.add(EXCEPTION_MARKER);
66
67 ENTRY_MESSAGE_ARRAY[0] = ENTRY_MESSAGE_0;
68 ENTRY_MESSAGE_ARRAY[1] = ENTRY_MESSAGE_1;
69 ENTRY_MESSAGE_ARRAY[2] = ENTRY_MESSAGE_2;
70 ENTRY_MESSAGE_ARRAY[3] = ENTRY_MESSAGE_3;
71 ENTRY_MESSAGE_ARRAY[4] = ENTRY_MESSAGE_4;
72 }
73
74 public enum Level {
75 TRACE("TRACE", LocationAwareLogger.TRACE_INT), DEBUG("DEBUG", LocationAwareLogger.DEBUG_INT), INFO("INFO", LocationAwareLogger.INFO_INT), WARN("WARN",
76 LocationAwareLogger.WARN_INT), ERROR("ERROR", LocationAwareLogger.ERROR_INT);
77
78 private final String name;
79 private final int level;
80
81 public String toString() {
82 return this.name;
83 }
84
85 public int intValue() {
86 return this.level;
87 }
88
89 private Level(String name, int level) {
90 this.name = name;
91 this.level = level;
92 }
93 }
94
95 /**
96 * Given an underlying logger, construct an XLogger
97 *
98 * @param logger
99 * underlying logger
100 */
101 public XLogger(Logger logger) {
102 // If class B extends A, assuming B does not override method x(), the caller
103 // of new B().x() is A and not B, see also
104 // http://jira.qos.ch/browse/SLF4J-105
105 super(logger, LoggerWrapper.class.getName());
106 }
107
108 /**
109 * Log method entry.
110 *
111 * @param argArray
112 * supplied parameters
113 */
114 public void entry(Object... argArray) {
115 if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
116 String messagePattern = null;
117 if (argArray.length < ENTRY_MESSAGE_ARRAY_LEN) {
118 messagePattern = ENTRY_MESSAGE_ARRAY[argArray.length];
119 } else {
120 messagePattern = buildMessagePattern(argArray.length);
121 }
122 FormattingTuple tp = MessageFormatter.arrayFormat(messagePattern, argArray);
123 ((LocationAwareLogger) logger).log(ENTRY_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), argArray, tp.getThrowable());
124 }
125 }
126
127 /**
128 * Log method exit
129 */
130 public void exit() {
131 if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
132 ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, EXIT_MESSAGE_0, null, null);
133 }
134 }
135
136 /**
137 * Log method exit
138 *
139 * @param result
140 * The result of the method being exited
141 */
142 public <T> T exit(T result) {
143 if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
144 FormattingTuple tp = MessageFormatter.format(EXIT_MESSAGE_1, result);
145 ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), new Object[] { result }, tp.getThrowable());
146 }
147 return result;
148 }
149
150 /**
151 * Log an exception being thrown. The generated log event uses Level ERROR.
152 *
153 * @param throwable
154 * the exception being caught.
155 */
156 public <T extends Throwable> T throwing(T throwable) {
157 if (instanceofLAL) {
158 ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "throwing", null, throwable);
159 }
160 return throwable;
161 }
162
163 /**
164 * Log an exception being thrown allowing the log level to be specified.
165 *
166 * @param level
167 * the logging level to use.
168 * @param throwable
169 * the exception being caught.
170 */
171 public <T extends Throwable> T throwing(Level level, T throwable) {
172 if (instanceofLAL) {
173 ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, level.level, "throwing", null, throwable);
174 }
175 return throwable;
176 }
177
178 /**
179 * Log an exception being caught. The generated log event uses Level ERROR.
180 *
181 * @param throwable
182 * the exception being caught.
183 */
184 public void catching(Throwable throwable) {
185 if (instanceofLAL) {
186 ((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "catching", null, throwable);
187 }
188 }
189
190 /**
191 * Log an exception being caught allowing the log level to be specified.
192 *
193 * @param level
194 * the logging level to use.
195 * @param throwable
196 * the exception being caught.
197 */
198 public void catching(Level level, Throwable throwable) {
199 if (instanceofLAL) {
200 ((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, level.level, "catching", null, throwable);
201 }
202 }
203
204 private static String buildMessagePattern(int len) {
205 StringBuilder sb = new StringBuilder();
206 sb.append(" entry with (");
207 for (int i = 0; i < len; i++) {
208 sb.append("{}");
209 if (i != len - 1)
210 sb.append(", ");
211 }
212 sb.append(')');
213 return sb.toString();
214 }
215 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28 import org.slf4j.MarkerFactory;
29 import org.slf4j.helpers.FormattingTuple;
30 import org.slf4j.helpers.MessageFormatter;
31 import org.slf4j.spi.LocationAwareLogger;
32
33 /**
34 * A utility that provides standard mechanisms for logging certain kinds of
35 * activities.
36 *
37 * @author Ralph Goers
38 * @author Ceki G&uuml;lc&uuml;
39 */
40 public class XLogger extends LoggerWrapper implements Logger {
41
42 private static final String FQCN = XLogger.class.getName();
43 static Marker FLOW_MARKER = MarkerFactory.getMarker("FLOW");
44 static Marker ENTRY_MARKER = MarkerFactory.getMarker("ENTRY");
45 static Marker EXIT_MARKER = MarkerFactory.getMarker("EXIT");
46
47 static Marker EXCEPTION_MARKER = MarkerFactory.getMarker("EXCEPTION");
48 static Marker THROWING_MARKER = MarkerFactory.getMarker("THROWING");
49 static Marker CATCHING_MARKER = MarkerFactory.getMarker("CATCHING");
50
51 static String EXIT_MESSAGE_0 = "exit";
52 static String EXIT_MESSAGE_1 = "exit with ({})";
53
54 static String ENTRY_MESSAGE_0 = "entry";
55 static String ENTRY_MESSAGE_1 = "entry with ({})";
56 static String ENTRY_MESSAGE_2 = "entry with ({}, {})";
57 static String ENTRY_MESSAGE_3 = "entry with ({}, {}, {})";
58 static String ENTRY_MESSAGE_4 = "entry with ({}, {}, {}, {})";
59 static int ENTRY_MESSAGE_ARRAY_LEN = 5;
60 static String[] ENTRY_MESSAGE_ARRAY = new String[ENTRY_MESSAGE_ARRAY_LEN];
61 static {
62 ENTRY_MARKER.add(FLOW_MARKER);
63 EXIT_MARKER.add(FLOW_MARKER);
64 THROWING_MARKER.add(EXCEPTION_MARKER);
65 CATCHING_MARKER.add(EXCEPTION_MARKER);
66
67 ENTRY_MESSAGE_ARRAY[0] = ENTRY_MESSAGE_0;
68 ENTRY_MESSAGE_ARRAY[1] = ENTRY_MESSAGE_1;
69 ENTRY_MESSAGE_ARRAY[2] = ENTRY_MESSAGE_2;
70 ENTRY_MESSAGE_ARRAY[3] = ENTRY_MESSAGE_3;
71 ENTRY_MESSAGE_ARRAY[4] = ENTRY_MESSAGE_4;
72 }
73
74 public enum Level {
75 TRACE("TRACE", LocationAwareLogger.TRACE_INT), DEBUG("DEBUG", LocationAwareLogger.DEBUG_INT), INFO("INFO", LocationAwareLogger.INFO_INT), WARN("WARN",
76 LocationAwareLogger.WARN_INT), ERROR("ERROR", LocationAwareLogger.ERROR_INT);
77
78 private final String name;
79 private final int level;
80
81 public String toString() {
82 return this.name;
83 }
84
85 public int intValue() {
86 return this.level;
87 }
88
89 private Level(String name, int level) {
90 this.name = name;
91 this.level = level;
92 }
93 }
94
95 /**
96 * Given an underlying logger, construct an XLogger
97 *
98 * @param logger
99 * underlying logger
100 */
101 public XLogger(Logger logger) {
102 // If class B extends A, assuming B does not override method x(), the caller
103 // of new B().x() is A and not B, see also
104 // http://jira.qos.ch/browse/SLF4J-105
105 super(logger, LoggerWrapper.class.getName());
106 }
107
108 /**
109 * Log method entry.
110 *
111 * @param argArray
112 * supplied parameters
113 */
114 public void entry(Object... argArray) {
115 if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
116 String messagePattern = null;
117 if (argArray.length < ENTRY_MESSAGE_ARRAY_LEN) {
118 messagePattern = ENTRY_MESSAGE_ARRAY[argArray.length];
119 } else {
120 messagePattern = buildMessagePattern(argArray.length);
121 }
122 FormattingTuple tp = MessageFormatter.arrayFormat(messagePattern, argArray);
123 ((LocationAwareLogger) logger).log(ENTRY_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), argArray, tp.getThrowable());
124 }
125 }
126
127 /**
128 * Log method exit
129 */
130 public void exit() {
131 if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
132 ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, EXIT_MESSAGE_0, null, null);
133 }
134 }
135
136 /**
137 * Log method exit
138 *
139 * @param result
140 * The result of the method being exited
141 */
142 public <T> T exit(T result) {
143 if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
144 FormattingTuple tp = MessageFormatter.format(EXIT_MESSAGE_1, result);
145 ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), new Object[] { result }, tp.getThrowable());
146 }
147 return result;
148 }
149
150 /**
151 * Log an exception being thrown. The generated log event uses Level ERROR.
152 *
153 * @param throwable
154 * the exception being caught.
155 */
156 public <T extends Throwable> T throwing(T throwable) {
157 if (instanceofLAL) {
158 ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "throwing", null, throwable);
159 }
160 return throwable;
161 }
162
163 /**
164 * Log an exception being thrown allowing the log level to be specified.
165 *
166 * @param level
167 * the logging level to use.
168 * @param throwable
169 * the exception being caught.
170 */
171 public <T extends Throwable> T throwing(Level level, T throwable) {
172 if (instanceofLAL) {
173 ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, level.level, "throwing", null, throwable);
174 }
175 return throwable;
176 }
177
178 /**
179 * Log an exception being caught. The generated log event uses Level ERROR.
180 *
181 * @param throwable
182 * the exception being caught.
183 */
184 public void catching(Throwable throwable) {
185 if (instanceofLAL) {
186 ((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "catching", null, throwable);
187 }
188 }
189
190 /**
191 * Log an exception being caught allowing the log level to be specified.
192 *
193 * @param level
194 * the logging level to use.
195 * @param throwable
196 * the exception being caught.
197 */
198 public void catching(Level level, Throwable throwable) {
199 if (instanceofLAL) {
200 ((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, level.level, "catching", null, throwable);
201 }
202 }
203
204 private static String buildMessagePattern(int len) {
205 StringBuilder sb = new StringBuilder();
206 sb.append(" entry with (");
207 for (int i = 0; i < len; i++) {
208 sb.append("{}");
209 if (i != len - 1)
210 sb.append(", ");
211 }
212 sb.append(')');
213 return sb.toString();
214 }
215 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.slf4j.LoggerFactory;
27
28 /**
29 *
30 * This class is essentially a wrapper around an
31 * {@link LoggerFactory} producing {@link XLogger} instances.
32 *
33 * <p>Contrary to {@link LoggerFactory#getLogger(String)} method of
34 * {@link LoggerFactory}, each call to {@link #getXLogger(String)}
35 * produces a new instance of <code>XLogger</code>. This should not matter
36 * because an <code>XLogger</code> instance does not have any state beyond that of
37 * the {@link org.slf4j.Logger Logger} instance it wraps.
38 *
39 * @author Ralph Goers
40 * @author Ceki G&uuml;lc&uuml;
41 */
42 public class XLoggerFactory {
43
44 /**
45 * Get an XLogger instance by name.
46 *
47 * @param name
48 * @return XLogger instance
49 */
50 public static XLogger getXLogger(String name) {
51 return new XLogger(LoggerFactory.getLogger(name));
52 }
53
54 /**
55 * Get a new XLogger instance by class. The returned XLogger
56 * will be named after the class.
57 *
58 * @param clazz
59 * @return XLogger instance by name
60 */
61 public static XLogger getXLogger(Class<?> clazz) {
62 return getXLogger(clazz.getName());
63 }
64 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.slf4j.LoggerFactory;
27
28 /**
29 *
30 * This class is essentially a wrapper around an
31 * {@link LoggerFactory} producing {@link XLogger} instances.
32 *
33 * <p>Contrary to {@link LoggerFactory#getLogger(String)} method of
34 * {@link LoggerFactory}, each call to {@link #getXLogger(String)}
35 * produces a new instance of <code>XLogger</code>. This should not matter
36 * because an <code>XLogger</code> instance does not have any state beyond that of
37 * the {@link org.slf4j.Logger Logger} instance it wraps.
38 *
39 * @author Ralph Goers
40 * @author Ceki G&uuml;lc&uuml;
41 */
42 public class XLoggerFactory {
43
44 /**
45 * Get an XLogger instance by name.
46 *
47 * @param name
48 * @return XLogger instance
49 */
50 public static XLogger getXLogger(String name) {
51 return new XLogger(LoggerFactory.getLogger(name));
52 }
53
54 /**
55 * Get a new XLogger instance by class. The returned XLogger
56 * will be named after the class.
57 *
58 * @param clazz
59 * @return XLogger instance by name
60 */
61 public static XLogger getXLogger(Class<?> clazz) {
62 return getXLogger(clazz.getName());
63 }
64 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>Localized logging using the <a href="http://cal10n.qos.ch">CAL10N</a> API.</p>
10 </body>
11 </html>
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>Localized logging using the <a href="http://cal10n.qos.ch">CAL10N</a> API.</p>
10 </body>
11 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.instrumentation;
25
26 import javassist.CtBehavior;
27 import javassist.CtClass;
28 import javassist.CtMethod;
29 import javassist.Modifier;
30 import javassist.NotFoundException;
31 import javassist.bytecode.AttributeInfo;
32 import javassist.bytecode.CodeAttribute;
33 import javassist.bytecode.LocalVariableAttribute;
34
35 /**
36 * Helper methods for Javassist functionality.
37 *
38 */
39 public class JavassistHelper {
40
41 /**
42 * Create a javassist source snippet which either is empty (for anything
43 * which does not return a value) or a explanatory text around the $_
44 * javassist return value variable.
45 *
46 * @param method
47 * descriptor of method
48 * @return source snippet
49 * @throws NotFoundException
50 */
51 public static String returnValue(CtBehavior method) throws NotFoundException {
52
53 String returnValue = "";
54 if (methodReturnsValue(method)) {
55 returnValue = " returns: \" + $_ + \".";
56 }
57 return returnValue;
58 }
59
60 /**
61 * determine if the given method returns a value, and return true if so.
62 * false otherwise.
63 *
64 * @param method
65 * @return
66 * @throws NotFoundException
67 */
68 private static boolean methodReturnsValue(CtBehavior method) throws NotFoundException {
69
70 if (method instanceof CtMethod == false) {
71 return false;
72 }
73
74 CtClass returnType = ((CtMethod) method).getReturnType();
75 String returnTypeName = returnType.getName();
76
77 boolean isVoidMethod = "void".equals(returnTypeName);
78
79 boolean methodReturnsValue = isVoidMethod == false;
80 return methodReturnsValue;
81 }
82
83 /**
84 * Return javassist source snippet which lists all the parameters and their
85 * values. If available the source names are extracted from the debug
86 * information and used, otherwise just a number is shown.
87 *
88 * @param method
89 * @return
90 * @throws NotFoundException
91 */
92 public static String getSignature(CtBehavior method) throws NotFoundException {
93
94 CtClass[] parameterTypes = method.getParameterTypes();
95
96 CodeAttribute codeAttribute = method.getMethodInfo().getCodeAttribute();
97
98 LocalVariableAttribute locals = null;
99
100 if (codeAttribute != null) {
101 AttributeInfo attribute;
102 attribute = codeAttribute.getAttribute("LocalVariableTable");
103 locals = (LocalVariableAttribute) attribute;
104 }
105
106 String methodName = method.getName();
107
108 StringBuilder sb = new StringBuilder(methodName).append("(\" ");
109 for (int i = 0; i < parameterTypes.length; i++) {
110 if (i > 0) {
111 // add a comma and a space between printed values
112 sb.append(" + \", \" ");
113 }
114
115 CtClass parameterType = parameterTypes[i];
116 boolean isArray = parameterType.isArray();
117 CtClass arrayType = parameterType.getComponentType();
118 if (isArray) {
119 while (arrayType.isArray()) {
120 arrayType = arrayType.getComponentType();
121 }
122 }
123
124 sb.append(" + \"");
125 try {
126 sb.append(parameterNameFor(method, locals, i));
127 } catch (Exception e) {
128 sb.append(i + 1);
129 }
130 sb.append("\" + \"=");
131
132 if (parameterType.isPrimitive()) {
133 // let the compiler handle primitive -> string
134 sb.append("\"+ $").append(i + 1);
135 } else {
136 String s = "org.slf4j.instrumentation.ToStringHelper.render";
137 sb.append("\"+ ").append(s).append("($").append(i + 1).append(')');
138 }
139 }
140 sb.append("+\")");
141
142 String signature = sb.toString();
143 return signature;
144 }
145
146 /**
147 * Determine the name of parameter with index i in the given method. Use the
148 * locals attributes about local variables from the classfile. Note: This is
149 * still work in progress.
150 *
151 * @param method
152 * @param locals
153 * @param i
154 * @return the name of the parameter if available or a number if not.
155 */
156 static String parameterNameFor(CtBehavior method, LocalVariableAttribute locals, int i) {
157
158 if (locals == null) {
159 return Integer.toString(i + 1);
160 }
161
162 int modifiers = method.getModifiers();
163
164 int j = i;
165
166 if (Modifier.isSynchronized(modifiers)) {
167 // skip object to synchronize upon.
168 j++;
169 // System.err.println("Synchronized");
170 }
171 if (Modifier.isStatic(modifiers) == false) {
172 // skip "this"
173 j++;
174 // System.err.println("Instance");
175 }
176 String variableName = locals.variableName(j);
177 // if (variableName.equals("this")) {
178 // System.err.println("'this' returned as a parameter name for "
179 // + method.getName() + " index " + j
180 // +
181 // ", names are probably shifted. Please submit source for class in slf4j bugreport");
182 // }
183 return variableName;
184 }
185 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.instrumentation;
25
26 import javassist.CtBehavior;
27 import javassist.CtClass;
28 import javassist.CtMethod;
29 import javassist.Modifier;
30 import javassist.NotFoundException;
31 import javassist.bytecode.AttributeInfo;
32 import javassist.bytecode.CodeAttribute;
33 import javassist.bytecode.LocalVariableAttribute;
34
35 /**
36 * Helper methods for Javassist functionality.
37 *
38 */
39 public class JavassistHelper {
40
41 /**
42 * Create a javassist source snippet which either is empty (for anything
43 * which does not return a value) or a explanatory text around the $_
44 * javassist return value variable.
45 *
46 * @param method
47 * descriptor of method
48 * @return source snippet
49 * @throws NotFoundException
50 */
51 public static String returnValue(CtBehavior method) throws NotFoundException {
52
53 String returnValue = "";
54 if (methodReturnsValue(method)) {
55 returnValue = " returns: \" + $_ + \".";
56 }
57 return returnValue;
58 }
59
60 /**
61 * determine if the given method returns a value, and return true if so.
62 * false otherwise.
63 *
64 * @param method
65 * @return
66 * @throws NotFoundException
67 */
68 private static boolean methodReturnsValue(CtBehavior method) throws NotFoundException {
69
70 if (method instanceof CtMethod == false) {
71 return false;
72 }
73
74 CtClass returnType = ((CtMethod) method).getReturnType();
75 String returnTypeName = returnType.getName();
76
77 boolean isVoidMethod = "void".equals(returnTypeName);
78
79 boolean methodReturnsValue = isVoidMethod == false;
80 return methodReturnsValue;
81 }
82
83 /**
84 * Return javassist source snippet which lists all the parameters and their
85 * values. If available the source names are extracted from the debug
86 * information and used, otherwise just a number is shown.
87 *
88 * @param method
89 * @return
90 * @throws NotFoundException
91 */
92 public static String getSignature(CtBehavior method) throws NotFoundException {
93
94 CtClass[] parameterTypes = method.getParameterTypes();
95
96 CodeAttribute codeAttribute = method.getMethodInfo().getCodeAttribute();
97
98 LocalVariableAttribute locals = null;
99
100 if (codeAttribute != null) {
101 AttributeInfo attribute;
102 attribute = codeAttribute.getAttribute("LocalVariableTable");
103 locals = (LocalVariableAttribute) attribute;
104 }
105
106 String methodName = method.getName();
107
108 StringBuilder sb = new StringBuilder(methodName).append("(\" ");
109 for (int i = 0; i < parameterTypes.length; i++) {
110 if (i > 0) {
111 // add a comma and a space between printed values
112 sb.append(" + \", \" ");
113 }
114
115 CtClass parameterType = parameterTypes[i];
116 boolean isArray = parameterType.isArray();
117 CtClass arrayType = parameterType.getComponentType();
118 if (isArray) {
119 while (arrayType.isArray()) {
120 arrayType = arrayType.getComponentType();
121 }
122 }
123
124 sb.append(" + \"");
125 try {
126 sb.append(parameterNameFor(method, locals, i));
127 } catch (Exception e) {
128 sb.append(i + 1);
129 }
130 sb.append("\" + \"=");
131
132 if (parameterType.isPrimitive()) {
133 // let the compiler handle primitive -> string
134 sb.append("\"+ $").append(i + 1);
135 } else {
136 String s = "org.slf4j.instrumentation.ToStringHelper.render";
137 sb.append("\"+ ").append(s).append("($").append(i + 1).append(')');
138 }
139 }
140 sb.append("+\")");
141
142 String signature = sb.toString();
143 return signature;
144 }
145
146 /**
147 * Determine the name of parameter with index i in the given method. Use the
148 * locals attributes about local variables from the classfile. Note: This is
149 * still work in progress.
150 *
151 * @param method
152 * @param locals
153 * @param i
154 * @return the name of the parameter if available or a number if not.
155 */
156 static String parameterNameFor(CtBehavior method, LocalVariableAttribute locals, int i) {
157
158 if (locals == null) {
159 return Integer.toString(i + 1);
160 }
161
162 int modifiers = method.getModifiers();
163
164 int j = i;
165
166 if (Modifier.isSynchronized(modifiers)) {
167 // skip object to synchronize upon.
168 j++;
169 // System.err.println("Synchronized");
170 }
171 if (Modifier.isStatic(modifiers) == false) {
172 // skip "this"
173 j++;
174 // System.err.println("Instance");
175 }
176 String variableName = locals.variableName(j);
177 // if (variableName.equals("this")) {
178 // System.err.println("'this' returned as a parameter name for "
179 // + method.getName() + " index " + j
180 // +
181 // ", names are probably shifted. Please submit source for class in slf4j bugreport");
182 // }
183 return variableName;
184 }
185 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 /**
25 *
26 */
27 package org.slf4j.instrumentation;
28
29 import static org.slf4j.helpers.MessageFormatter.format;
30
31 import java.io.ByteArrayInputStream;
32 import java.lang.instrument.ClassFileTransformer;
33 import java.security.ProtectionDomain;
34
35 import javassist.CannotCompileException;
36 import javassist.ClassPool;
37 import javassist.CtBehavior;
38 import javassist.CtClass;
39 import javassist.CtField;
40 import javassist.NotFoundException;
41
42 import org.slf4j.helpers.MessageFormatter;
43
44 /**
45 * <p>
46 * LogTransformer does the work of analyzing each class, and if appropriate add
47 * log statements to each method to allow logging entry/exit.
48 * </p>
49 * <p>
50 * This class is based on the article <a href="http://today.java.net/pub/a/today/2008/04/24/add-logging-at-class-load-time-with-instrumentation.html"
51 * >Add Logging at Class Load Time with Java Instrumentation</a>.
52 * </p>
53 */
54 public class LogTransformer implements ClassFileTransformer {
55
56 /**
57 * Builder provides a flexible way of configuring some of many options on the
58 * parent class instead of providing many constructors.
59 *
60 * <a href="http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html">http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html</a>
61 *
62 */
63 public static class Builder {
64
65 /**
66 * Build and return the LogTransformer corresponding to the options set in
67 * this Builder.
68 *
69 * @return
70 */
71 public LogTransformer build() {
72 if (verbose) {
73 System.err.println("Creating LogTransformer");
74 }
75 return new LogTransformer(this);
76 }
77
78 boolean addEntryExit;
79
80 /**
81 * Should each method log entry (with parameters) and exit (with parameters
82 * and return value)?
83 *
84 * @param b
85 * value of flag
86 * @return
87 */
88 public Builder addEntryExit(boolean b) {
89 addEntryExit = b;
90 return this;
91 }
92
93 boolean addVariableAssignment;
94
95 // private Builder addVariableAssignment(boolean b) {
96 // System.err.println("cannot currently log variable assignments.");
97 // addVariableAssignment = b;
98 // return this;
99 // }
100
101 boolean verbose;
102
103 /**
104 * Should LogTransformer be verbose in what it does? This currently list the
105 * names of the classes being processed.
106 *
107 * @param b
108 * @return
109 */
110 public Builder verbose(boolean b) {
111 verbose = b;
112 return this;
113 }
114
115 String[] ignore = { "org/slf4j/", "ch/qos/logback/", "org/apache/log4j/" };
116
117 public Builder ignore(String[] strings) {
118 this.ignore = strings;
119 return this;
120 }
121
122 private String level = "info";
123
124 public Builder level(String level) {
125 level = level.toLowerCase();
126 if (level.equals("info") || level.equals("debug") || level.equals("trace")) {
127 this.level = level;
128 } else {
129 if (verbose) {
130 System.err.println("level not info/debug/trace : " + level);
131 }
132 }
133 return this;
134 }
135 }
136
137 private String level;
138 private String levelEnabled;
139
140 private LogTransformer(Builder builder) {
141 String s = "WARNING: javassist not available on classpath for javaagent, log statements will not be added";
142 try {
143 if (Class.forName("javassist.ClassPool") == null) {
144 System.err.println(s);
145 }
146 } catch (ClassNotFoundException e) {
147 System.err.println(s);
148 }
149
150 this.addEntryExit = builder.addEntryExit;
151 // this.addVariableAssignment = builder.addVariableAssignment;
152 this.verbose = builder.verbose;
153 this.ignore = builder.ignore;
154 this.level = builder.level;
155 this.levelEnabled = "is" + builder.level.substring(0, 1).toUpperCase() + builder.level.substring(1) + "Enabled";
156 }
157
158 private boolean addEntryExit;
159 // private boolean addVariableAssignment;
160 private boolean verbose;
161 private String[] ignore;
162
163 public byte[] transform(ClassLoader loader, String className, Class<?> clazz, ProtectionDomain domain, byte[] bytes) {
164
165 try {
166 return transform0(className, clazz, domain, bytes);
167 } catch (Exception e) {
168 System.err.println("Could not instrument " + className);
169 e.printStackTrace();
170 return bytes;
171 }
172 }
173
174 /**
175 * transform0 sees if the className starts with any of the namespaces to
176 * ignore, if so it is returned unchanged. Otherwise it is processed by
177 * doClass(...)
178 *
179 * @param className
180 * @param clazz
181 * @param domain
182 * @param bytes
183 * @return
184 */
185
186 private byte[] transform0(String className, Class<?> clazz, ProtectionDomain domain, byte[] bytes) {
187
188 try {
189 for (int i = 0; i < ignore.length; i++) {
190 if (className.startsWith(ignore[i])) {
191 return bytes;
192 }
193 }
194 String slf4jName = "org.slf4j.LoggerFactory";
195 try {
196 if (domain != null && domain.getClassLoader() != null) {
197 domain.getClassLoader().loadClass(slf4jName);
198 } else {
199 if (verbose) {
200 System.err.println("Skipping " + className + " as it doesn't have a domain or a class loader.");
201 }
202 return bytes;
203 }
204 } catch (ClassNotFoundException e) {
205 if (verbose) {
206 System.err.println("Skipping " + className + " as slf4j is not available to it");
207 }
208 return bytes;
209 }
210 if (verbose) {
211 System.err.println("Processing " + className);
212 }
213 return doClass(className, clazz, bytes);
214 } catch (Throwable e) {
215 System.out.println("e = " + e);
216 return bytes;
217 }
218 }
219
220 private String loggerName;
221
222 /**
223 * doClass() process a single class by first creates a class description from
224 * the byte codes. If it is a class (i.e. not an interface) the methods
225 * defined have bodies, and a static final logger object is added with the
226 * name of this class as an argument, and each method then gets processed with
227 * doMethod(...) to have logger calls added.
228 *
229 * @param name
230 * class name (slashes separate, not dots)
231 * @param clazz
232 * @param b
233 * @return
234 */
235 private byte[] doClass(String name, Class<?> clazz, byte[] b) {
236 ClassPool pool = ClassPool.getDefault();
237 CtClass cl = null;
238 try {
239 cl = pool.makeClass(new ByteArrayInputStream(b));
240 if (cl.isInterface() == false) {
241
242 loggerName = "_____log";
243
244 // We have to declare the log variable.
245
246 String pattern1 = "private static org.slf4j.Logger {};";
247 String loggerDefinition = format(pattern1, loggerName).getMessage();
248 CtField field = CtField.make(loggerDefinition, cl);
249
250 // and assign it the appropriate value.
251
252 String pattern2 = "org.slf4j.LoggerFactory.getLogger({}.class);";
253 String replace = name.replace('/', '.');
254 String getLogger = format(pattern2, replace).getMessage();
255
256 cl.addField(field, getLogger);
257
258 // then check every behaviour (which includes methods). We are
259 // only
260 // interested in non-empty ones, as they have code.
261 // NOTE: This will be changed, as empty methods should be
262 // instrumented too.
263
264 CtBehavior[] methods = cl.getDeclaredBehaviors();
265 for (int i = 0; i < methods.length; i++) {
266 if (methods[i].isEmpty() == false) {
267 doMethod(methods[i]);
268 }
269 }
270 b = cl.toBytecode();
271 }
272 } catch (Exception e) {
273 System.err.println("Could not instrument " + name + ", " + e);
274 e.printStackTrace(System.err);
275 } finally {
276 if (cl != null) {
277 cl.detach();
278 }
279 }
280 return b;
281 }
282
283 /**
284 * process a single method - this means add entry/exit logging if requested.
285 * It is only called for methods with a body.
286 *
287 * @param method
288 * method to work on
289 * @throws NotFoundException
290 * @throws CannotCompileException
291 */
292 private void doMethod(CtBehavior method) throws NotFoundException, CannotCompileException {
293
294 String signature = JavassistHelper.getSignature(method);
295 String returnValue = JavassistHelper.returnValue(method);
296
297 if (addEntryExit) {
298 String messagePattern = "if ({}.{}()) {}.{}(\">> {}\");";
299 Object[] arg1 = new Object[] { loggerName, levelEnabled, loggerName, level, signature };
300 String before = MessageFormatter.arrayFormat(messagePattern, arg1).getMessage();
301 // System.out.println(before);
302 method.insertBefore(before);
303
304 String messagePattern2 = "if ({}.{}()) {}.{}(\"<< {}{}\");";
305 Object[] arg2 = new Object[] { loggerName, levelEnabled, loggerName, level, signature, returnValue };
306 String after = MessageFormatter.arrayFormat(messagePattern2, arg2).getMessage();
307 // System.out.println(after);
308 method.insertAfter(after);
309 }
310 }
311 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 /**
25 *
26 */
27 package org.slf4j.instrumentation;
28
29 import static org.slf4j.helpers.MessageFormatter.format;
30
31 import java.io.ByteArrayInputStream;
32 import java.lang.instrument.ClassFileTransformer;
33 import java.security.ProtectionDomain;
34
35 import javassist.CannotCompileException;
36 import javassist.ClassPool;
37 import javassist.CtBehavior;
38 import javassist.CtClass;
39 import javassist.CtField;
40 import javassist.NotFoundException;
41
42 import org.slf4j.helpers.MessageFormatter;
43
44 /**
45 * <p>
46 * LogTransformer does the work of analyzing each class, and if appropriate add
47 * log statements to each method to allow logging entry/exit.
48 * </p>
49 * <p>
50 * This class is based on the article <a href="http://today.java.net/pub/a/today/2008/04/24/add-logging-at-class-load-time-with-instrumentation.html"
51 * >Add Logging at Class Load Time with Java Instrumentation</a>.
52 * </p>
53 */
54 public class LogTransformer implements ClassFileTransformer {
55
56 /**
57 * Builder provides a flexible way of configuring some of many options on the
58 * parent class instead of providing many constructors.
59 *
60 * <a href="http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html">http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html</a>
61 *
62 */
63 public static class Builder {
64
65 /**
66 * Build and return the LogTransformer corresponding to the options set in
67 * this Builder.
68 *
69 * @return
70 */
71 public LogTransformer build() {
72 if (verbose) {
73 System.err.println("Creating LogTransformer");
74 }
75 return new LogTransformer(this);
76 }
77
78 boolean addEntryExit;
79
80 /**
81 * Should each method log entry (with parameters) and exit (with parameters
82 * and return value)?
83 *
84 * @param b
85 * value of flag
86 * @return
87 */
88 public Builder addEntryExit(boolean b) {
89 addEntryExit = b;
90 return this;
91 }
92
93 boolean addVariableAssignment;
94
95 // private Builder addVariableAssignment(boolean b) {
96 // System.err.println("cannot currently log variable assignments.");
97 // addVariableAssignment = b;
98 // return this;
99 // }
100
101 boolean verbose;
102
103 /**
104 * Should LogTransformer be verbose in what it does? This currently list the
105 * names of the classes being processed.
106 *
107 * @param b
108 * @return
109 */
110 public Builder verbose(boolean b) {
111 verbose = b;
112 return this;
113 }
114
115 String[] ignore = { "org/slf4j/", "ch/qos/logback/", "org/apache/log4j/" };
116
117 public Builder ignore(String[] strings) {
118 this.ignore = strings;
119 return this;
120 }
121
122 private String level = "info";
123
124 public Builder level(String level) {
125 level = level.toLowerCase();
126 if (level.equals("info") || level.equals("debug") || level.equals("trace")) {
127 this.level = level;
128 } else {
129 if (verbose) {
130 System.err.println("level not info/debug/trace : " + level);
131 }
132 }
133 return this;
134 }
135 }
136
137 private String level;
138 private String levelEnabled;
139
140 private LogTransformer(Builder builder) {
141 String s = "WARNING: javassist not available on classpath for javaagent, log statements will not be added";
142 try {
143 if (Class.forName("javassist.ClassPool") == null) {
144 System.err.println(s);
145 }
146 } catch (ClassNotFoundException e) {
147 System.err.println(s);
148 }
149
150 this.addEntryExit = builder.addEntryExit;
151 // this.addVariableAssignment = builder.addVariableAssignment;
152 this.verbose = builder.verbose;
153 this.ignore = builder.ignore;
154 this.level = builder.level;
155 this.levelEnabled = "is" + builder.level.substring(0, 1).toUpperCase() + builder.level.substring(1) + "Enabled";
156 }
157
158 private boolean addEntryExit;
159 // private boolean addVariableAssignment;
160 private boolean verbose;
161 private String[] ignore;
162
163 public byte[] transform(ClassLoader loader, String className, Class<?> clazz, ProtectionDomain domain, byte[] bytes) {
164
165 try {
166 return transform0(className, clazz, domain, bytes);
167 } catch (Exception e) {
168 System.err.println("Could not instrument " + className);
169 e.printStackTrace();
170 return bytes;
171 }
172 }
173
174 /**
175 * transform0 sees if the className starts with any of the namespaces to
176 * ignore, if so it is returned unchanged. Otherwise it is processed by
177 * doClass(...)
178 *
179 * @param className
180 * @param clazz
181 * @param domain
182 * @param bytes
183 * @return
184 */
185
186 private byte[] transform0(String className, Class<?> clazz, ProtectionDomain domain, byte[] bytes) {
187
188 try {
189 for (int i = 0; i < ignore.length; i++) {
190 if (className.startsWith(ignore[i])) {
191 return bytes;
192 }
193 }
194 String slf4jName = "org.slf4j.LoggerFactory";
195 try {
196 if (domain != null && domain.getClassLoader() != null) {
197 domain.getClassLoader().loadClass(slf4jName);
198 } else {
199 if (verbose) {
200 System.err.println("Skipping " + className + " as it doesn't have a domain or a class loader.");
201 }
202 return bytes;
203 }
204 } catch (ClassNotFoundException e) {
205 if (verbose) {
206 System.err.println("Skipping " + className + " as slf4j is not available to it");
207 }
208 return bytes;
209 }
210 if (verbose) {
211 System.err.println("Processing " + className);
212 }
213 return doClass(className, clazz, bytes);
214 } catch (Throwable e) {
215 System.out.println("e = " + e);
216 return bytes;
217 }
218 }
219
220 private String loggerName;
221
222 /**
223 * doClass() process a single class by first creates a class description from
224 * the byte codes. If it is a class (i.e. not an interface) the methods
225 * defined have bodies, and a static final logger object is added with the
226 * name of this class as an argument, and each method then gets processed with
227 * doMethod(...) to have logger calls added.
228 *
229 * @param name
230 * class name (slashes separate, not dots)
231 * @param clazz
232 * @param b
233 * @return
234 */
235 private byte[] doClass(String name, Class<?> clazz, byte[] b) {
236 ClassPool pool = ClassPool.getDefault();
237 CtClass cl = null;
238 try {
239 cl = pool.makeClass(new ByteArrayInputStream(b));
240 if (cl.isInterface() == false) {
241
242 loggerName = "_____log";
243
244 // We have to declare the log variable.
245
246 String pattern1 = "private static org.slf4j.Logger {};";
247 String loggerDefinition = format(pattern1, loggerName).getMessage();
248 CtField field = CtField.make(loggerDefinition, cl);
249
250 // and assign it the appropriate value.
251
252 String pattern2 = "org.slf4j.LoggerFactory.getLogger({}.class);";
253 String replace = name.replace('/', '.');
254 String getLogger = format(pattern2, replace).getMessage();
255
256 cl.addField(field, getLogger);
257
258 // then check every behaviour (which includes methods). We are
259 // only
260 // interested in non-empty ones, as they have code.
261 // NOTE: This will be changed, as empty methods should be
262 // instrumented too.
263
264 CtBehavior[] methods = cl.getDeclaredBehaviors();
265 for (int i = 0; i < methods.length; i++) {
266 if (methods[i].isEmpty() == false) {
267 doMethod(methods[i]);
268 }
269 }
270 b = cl.toBytecode();
271 }
272 } catch (Exception e) {
273 System.err.println("Could not instrument " + name + ", " + e);
274 e.printStackTrace(System.err);
275 } finally {
276 if (cl != null) {
277 cl.detach();
278 }
279 }
280 return b;
281 }
282
283 /**
284 * process a single method - this means add entry/exit logging if requested.
285 * It is only called for methods with a body.
286 *
287 * @param method
288 * method to work on
289 * @throws NotFoundException
290 * @throws CannotCompileException
291 */
292 private void doMethod(CtBehavior method) throws NotFoundException, CannotCompileException {
293
294 String signature = JavassistHelper.getSignature(method);
295 String returnValue = JavassistHelper.returnValue(method);
296
297 if (addEntryExit) {
298 String messagePattern = "if ({}.{}()) {}.{}(\">> {}\");";
299 Object[] arg1 = new Object[] { loggerName, levelEnabled, loggerName, level, signature };
300 String before = MessageFormatter.arrayFormat(messagePattern, arg1).getMessage();
301 // System.out.println(before);
302 method.insertBefore(before);
303
304 String messagePattern2 = "if ({}.{}()) {}.{}(\"<< {}{}\");";
305 Object[] arg2 = new Object[] { loggerName, levelEnabled, loggerName, level, signature, returnValue };
306 String after = MessageFormatter.arrayFormat(messagePattern2, arg2).getMessage();
307 // System.out.println(after);
308 method.insertAfter(after);
309 }
310 }
311 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.instrumentation;
25
26 import java.util.Map;
27 import java.util.WeakHashMap;
28
29 public class ToStringHelper {
30
31 /**
32 * Prefix to use at the start of the representation. Always used.
33 */
34 private static final String ARRAY_PREFIX = "[";
35
36 /**
37 * Suffix to use at the end of the representation. Always used.
38 */
39 private static final char ARRAY_SUFFIX = ']';
40
41 /**
42 * String separating each element when rendering an array. To be compatible
43 * with lists comma-space is used.
44 */
45
46 private static final char[] ELEMENT_SEPARATOR = ", ".toCharArray();
47
48 /**
49 * unrenderableClasses is essentially a Set of Class objects which has for
50 * some reason failed to render properly when invoked through a toString
51 * method call. To avoid memory leaks a data structure using weak references
52 * is needed, but unfortunately the runtime library does not contain a
53 * WeakHashSet class, so the behavior is emulated with a WeakHashmap with
54 * the class as the key, and a Long containing the value of
55 * System.currentTimeMilis when an instance of the class failed to render.
56 */
57
58 final static Map<Class<?>, Object> unrenderableClasses = new WeakHashMap<Class<?>, Object>();
59
60 /**
61 * Returns o.toString() unless it throws an exception (which causes it to be
62 * stored in unrenderableClasses) or already was present in
63 * unrenderableClasses. If so, the same string is returned as would have
64 * been returned by Object.toString(). Arrays get special treatment as they
65 * don't have usable toString methods.
66 *
67 * @param o
68 * incoming object to render.
69 * @return
70 */
71
72 public static String render(Object o) {
73 if (o == null) {
74 return String.valueOf(o);
75 }
76 Class<?> objectClass = o.getClass();
77
78 if (unrenderableClasses.containsKey(objectClass) == false) {
79 try {
80 if (objectClass.isArray()) {
81 return renderArray(o, objectClass).toString();
82 } else {
83 return o.toString();
84 }
85 } catch (Exception e) {
86 Long now = new Long(System.currentTimeMillis());
87
88 System.err.println("Disabling exception throwing class " + objectClass.getName() + ", " + e.getMessage());
89
90 unrenderableClasses.put(objectClass, now);
91 }
92 }
93 String name = o.getClass().getName();
94 return name + "@" + Integer.toHexString(o.hashCode());
95 }
96
97 /**
98 * renderArray returns an array similar to a List. If the array type is an
99 * object they are rendered with "render(object)" for each. If the array
100 * type is a primitive each element is added directly to the string buffer
101 * collecting the result.
102 *
103 * @param o
104 * @param objectClass
105 * @return
106 */
107 private static StringBuilder renderArray(Object o, Class<?> objectClass) {
108 Class<?> componentType = objectClass.getComponentType();
109 StringBuilder sb = new StringBuilder(ARRAY_PREFIX);
110
111 if (componentType.isPrimitive() == false) {
112 Object[] oa = (Object[]) o;
113 for (int i = 0; i < oa.length; i++) {
114 if (i > 0) {
115 sb.append(ELEMENT_SEPARATOR);
116 }
117 sb.append(render(oa[i]));
118 }
119 } else {
120 if (Boolean.TYPE.equals(componentType)) {
121 boolean[] ba = (boolean[]) o;
122 for (int i = 0; i < ba.length; i++) {
123 if (i > 0) {
124 sb.append(ELEMENT_SEPARATOR);
125 }
126 sb.append(ba[i]);
127 }
128 } else if (Integer.TYPE.equals(componentType)) {
129 int[] ia = (int[]) o;
130 for (int i = 0; i < ia.length; i++) {
131 if (i > 0) {
132 sb.append(ELEMENT_SEPARATOR);
133 }
134 sb.append(ia[i]);
135 }
136
137 } else if (Long.TYPE.equals(componentType)) {
138 long[] ia = (long[]) o;
139 for (int i = 0; i < ia.length; i++) {
140 if (i > 0) {
141 sb.append(ELEMENT_SEPARATOR);
142 }
143 sb.append(ia[i]);
144 }
145 } else if (Double.TYPE.equals(componentType)) {
146 double[] ia = (double[]) o;
147 for (int i = 0; i < ia.length; i++) {
148 if (i > 0) {
149 sb.append(ELEMENT_SEPARATOR);
150 }
151 sb.append(ia[i]);
152 }
153 } else if (Float.TYPE.equals(componentType)) {
154 float[] ia = (float[]) o;
155 for (int i = 0; i < ia.length; i++) {
156 if (i > 0) {
157 sb.append(ELEMENT_SEPARATOR);
158 }
159 sb.append(ia[i]);
160 }
161 } else if (Character.TYPE.equals(componentType)) {
162 char[] ia = (char[]) o;
163 for (int i = 0; i < ia.length; i++) {
164 if (i > 0) {
165 sb.append(ELEMENT_SEPARATOR);
166 }
167 sb.append(ia[i]);
168 }
169 } else if (Short.TYPE.equals(componentType)) {
170 short[] ia = (short[]) o;
171 for (int i = 0; i < ia.length; i++) {
172 if (i > 0) {
173 sb.append(ELEMENT_SEPARATOR);
174 }
175 sb.append(ia[i]);
176 }
177 } else if (Byte.TYPE.equals(componentType)) {
178 byte[] ia = (byte[]) o;
179 for (int i = 0; i < ia.length; i++) {
180 if (i > 0) {
181 sb.append(ELEMENT_SEPARATOR);
182 }
183 sb.append(ia[i]);
184 }
185 }
186 }
187 sb.append(ARRAY_SUFFIX);
188 return sb;
189 }
190 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.instrumentation;
25
26 import java.util.Map;
27 import java.util.WeakHashMap;
28
29 public class ToStringHelper {
30
31 /**
32 * Prefix to use at the start of the representation. Always used.
33 */
34 private static final String ARRAY_PREFIX = "[";
35
36 /**
37 * Suffix to use at the end of the representation. Always used.
38 */
39 private static final char ARRAY_SUFFIX = ']';
40
41 /**
42 * String separating each element when rendering an array. To be compatible
43 * with lists comma-space is used.
44 */
45
46 private static final char[] ELEMENT_SEPARATOR = ", ".toCharArray();
47
48 /**
49 * unrenderableClasses is essentially a Set of Class objects which has for
50 * some reason failed to render properly when invoked through a toString
51 * method call. To avoid memory leaks a data structure using weak references
52 * is needed, but unfortunately the runtime library does not contain a
53 * WeakHashSet class, so the behavior is emulated with a WeakHashmap with
54 * the class as the key, and a Long containing the value of
55 * System.currentTimeMilis when an instance of the class failed to render.
56 */
57
58 final static Map<Class<?>, Object> unrenderableClasses = new WeakHashMap<Class<?>, Object>();
59
60 /**
61 * Returns o.toString() unless it throws an exception (which causes it to be
62 * stored in unrenderableClasses) or already was present in
63 * unrenderableClasses. If so, the same string is returned as would have
64 * been returned by Object.toString(). Arrays get special treatment as they
65 * don't have usable toString methods.
66 *
67 * @param o
68 * incoming object to render.
69 * @return
70 */
71
72 public static String render(Object o) {
73 if (o == null) {
74 return String.valueOf(o);
75 }
76 Class<?> objectClass = o.getClass();
77
78 if (unrenderableClasses.containsKey(objectClass) == false) {
79 try {
80 if (objectClass.isArray()) {
81 return renderArray(o, objectClass).toString();
82 } else {
83 return o.toString();
84 }
85 } catch (Exception e) {
86 Long now = new Long(System.currentTimeMillis());
87
88 System.err.println("Disabling exception throwing class " + objectClass.getName() + ", " + e.getMessage());
89
90 unrenderableClasses.put(objectClass, now);
91 }
92 }
93 String name = o.getClass().getName();
94 return name + "@" + Integer.toHexString(o.hashCode());
95 }
96
97 /**
98 * renderArray returns an array similar to a List. If the array type is an
99 * object they are rendered with "render(object)" for each. If the array
100 * type is a primitive each element is added directly to the string buffer
101 * collecting the result.
102 *
103 * @param o
104 * @param objectClass
105 * @return
106 */
107 private static StringBuilder renderArray(Object o, Class<?> objectClass) {
108 Class<?> componentType = objectClass.getComponentType();
109 StringBuilder sb = new StringBuilder(ARRAY_PREFIX);
110
111 if (componentType.isPrimitive() == false) {
112 Object[] oa = (Object[]) o;
113 for (int i = 0; i < oa.length; i++) {
114 if (i > 0) {
115 sb.append(ELEMENT_SEPARATOR);
116 }
117 sb.append(render(oa[i]));
118 }
119 } else {
120 if (Boolean.TYPE.equals(componentType)) {
121 boolean[] ba = (boolean[]) o;
122 for (int i = 0; i < ba.length; i++) {
123 if (i > 0) {
124 sb.append(ELEMENT_SEPARATOR);
125 }
126 sb.append(ba[i]);
127 }
128 } else if (Integer.TYPE.equals(componentType)) {
129 int[] ia = (int[]) o;
130 for (int i = 0; i < ia.length; i++) {
131 if (i > 0) {
132 sb.append(ELEMENT_SEPARATOR);
133 }
134 sb.append(ia[i]);
135 }
136
137 } else if (Long.TYPE.equals(componentType)) {
138 long[] ia = (long[]) o;
139 for (int i = 0; i < ia.length; i++) {
140 if (i > 0) {
141 sb.append(ELEMENT_SEPARATOR);
142 }
143 sb.append(ia[i]);
144 }
145 } else if (Double.TYPE.equals(componentType)) {
146 double[] ia = (double[]) o;
147 for (int i = 0; i < ia.length; i++) {
148 if (i > 0) {
149 sb.append(ELEMENT_SEPARATOR);
150 }
151 sb.append(ia[i]);
152 }
153 } else if (Float.TYPE.equals(componentType)) {
154 float[] ia = (float[]) o;
155 for (int i = 0; i < ia.length; i++) {
156 if (i > 0) {
157 sb.append(ELEMENT_SEPARATOR);
158 }
159 sb.append(ia[i]);
160 }
161 } else if (Character.TYPE.equals(componentType)) {
162 char[] ia = (char[]) o;
163 for (int i = 0; i < ia.length; i++) {
164 if (i > 0) {
165 sb.append(ELEMENT_SEPARATOR);
166 }
167 sb.append(ia[i]);
168 }
169 } else if (Short.TYPE.equals(componentType)) {
170 short[] ia = (short[]) o;
171 for (int i = 0; i < ia.length; i++) {
172 if (i > 0) {
173 sb.append(ELEMENT_SEPARATOR);
174 }
175 sb.append(ia[i]);
176 }
177 } else if (Byte.TYPE.equals(componentType)) {
178 byte[] ia = (byte[]) o;
179 for (int i = 0; i < ia.length; i++) {
180 if (i > 0) {
181 sb.append(ELEMENT_SEPARATOR);
182 }
183 sb.append(ia[i]);
184 }
185 }
186 }
187 sb.append(ARRAY_SUFFIX);
188 return sb;
189 }
190 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>Java instrumentation routines for SLF4J.</p>
10
11 <p>Byte code instrumentation is an way to change behaviour of java
12 classes at <i>load time</i>. This is done in-between the original byte
13 codes are retrieved and the class object is constructed by the class
14 loader. Currently this depends on the javassist library from JBoss
15 (which in turn uses it extensively in their application server).</p>
16 </body>
17 </html>
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>Java instrumentation routines for SLF4J.</p>
10
11 <p>Byte code instrumentation is an way to change behaviour of java
12 classes at <i>load time</i>. This is done in-between the original byte
13 codes are retrieved and the class object is constructed by the class
14 loader. Currently this depends on the javassist library from JBoss
15 (which in turn uses it extensively in their application server).</p>
16 </body>
17 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 * An enum of supported time units.
28 *
29 * @author Ceki
30 *
31 */
32 public enum DurationUnit {
33 NANOSECOND, MICROSECOND, MILLISSECOND, SECOND;
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 * An enum of supported time units.
28 *
29 * @author Ceki
30 *
31 */
32 public enum DurationUnit {
33 NANOSECOND, MICROSECOND, MILLISSECOND, SECOND;
3434 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.slf4j.Logger;
30 import org.slf4j.Marker;
31 import org.slf4j.MarkerFactory;
32
33 // + Profiler [BAS]
34 // |-- elapsed time [doX] 0 milliseconds.
35 // |-- elapsed time [doYYYYY] 56 milliseconds.
36 // |--+ Profiler Y
37 // |-- elapsed time [doZ] 21 milliseconds.
38 // |-- elapsed time [doZ] 21 milliseconds.
39 // |-- Total elapsed time [Y] 78 milliseconds.
40 // |-- elapsed time [doZ] 21 milliseconds.
41 // |-- Total elapsed time [BAS] 78 milliseconds.
42
43 /**
44 * A poor man's profiler to measure the time elapsed performing some lengthy
45 * task.
46 *
47 * @author Ceki G&uuml;lc&uuml;
48 */
49 public class Profiler implements TimeInstrument {
50
51 final static String PROFILER_MARKER_NAME = "PROFILER";
52
53 final static int MIN_SW_NAME_LENGTH = 24;
54 final static int MIN_SW_ELAPSED_TIME_NUMBER_LENGTH = 9;
55
56 final String name;
57 final StopWatch globalStopWatch;
58
59 List<TimeInstrument> childTimeInstrumentList = new ArrayList<TimeInstrument>();
60
61 // optional field
62 ProfilerRegistry profilerRegistry;
63 // optional field
64 Logger logger;
65
66 public Profiler(String name) {
67 this.name = name;
68 this.globalStopWatch = new StopWatch(name);
69 }
70
71 public String getName() {
72 return name;
73 }
74
75 public ProfilerRegistry getProfilerRegistry() {
76 return profilerRegistry;
77 }
78
79 public void registerWith(ProfilerRegistry profilerRegistry) {
80 if (profilerRegistry == null) {
81 return;
82 }
83 this.profilerRegistry = profilerRegistry;
84 profilerRegistry.put(this);
85 }
86
87 public Logger getLogger() {
88 return logger;
89 }
90
91 public void setLogger(Logger logger) {
92 this.logger = logger;
93 }
94
95 /**
96 * Starts a child stop watch and stops any previously started time
97 * instruments.
98 */
99 public void start(String name) {
100 stopLastTimeInstrument();
101 StopWatch childSW = new StopWatch(name);
102 childTimeInstrumentList.add(childSW);
103 }
104
105 public Profiler startNested(String name) {
106 stopLastTimeInstrument();
107 Profiler nestedProfiler = new Profiler(name);
108 nestedProfiler.registerWith(profilerRegistry);
109 nestedProfiler.setLogger(logger);
110 childTimeInstrumentList.add(nestedProfiler);
111 return nestedProfiler;
112 }
113
114 TimeInstrument getLastTimeInstrument() {
115 if (childTimeInstrumentList.size() > 0) {
116 return childTimeInstrumentList.get(childTimeInstrumentList.size() - 1);
117 } else {
118 return null;
119 }
120 }
121
122 void stopLastTimeInstrument() {
123 TimeInstrument last = getLastTimeInstrument();
124 if (last != null) {
125 last.stop();
126 }
127 }
128
129 // void stopNestedProfilers() {
130 // for (Object child : childTimeInstrumentList) {
131 // if (child instanceof Profiler)
132 // ((Profiler) child).stop();
133 // }
134 // }
135
136 public long elapsedTime() {
137 return globalStopWatch.elapsedTime();
138 }
139
140 public TimeInstrument stop() {
141 stopLastTimeInstrument();
142 globalStopWatch.stop();
143 return this;
144 }
145
146 public TimeInstrumentStatus getStatus() {
147 return globalStopWatch.status;
148 }
149
150 /**
151 * This method is used in tests.
152 */
153 void sanityCheck() throws IllegalStateException {
154 if (getStatus() != TimeInstrumentStatus.STOPPED) {
155 throw new IllegalStateException("time instrument [" + getName() + " is not stopped");
156 }
157
158 long totalElapsed = globalStopWatch.elapsedTime();
159 long childTotal = 0;
160
161 for (TimeInstrument ti : childTimeInstrumentList) {
162 childTotal += ti.elapsedTime();
163 if (ti.getStatus() != TimeInstrumentStatus.STOPPED) {
164 throw new IllegalStateException("time instrument [" + ti.getName() + " is not stopped");
165 }
166 if (ti instanceof Profiler) {
167 Profiler nestedProfiler = (Profiler) ti;
168 nestedProfiler.sanityCheck();
169 }
170 }
171 if (totalElapsed < childTotal) {
172 throw new IllegalStateException("children have a higher accumulated elapsed time");
173 }
174 }
175
176 static String TOP_PROFILER_FIRST_PREFIX = "+";
177 static String NESTED_PROFILER_FIRST_PREFIX = "|---+";
178 static String TOTAL_ELAPSED = " Total ";
179 static String SUBTOTAL_ELAPSED = " Subtotal ";
180 static String ELAPSED_TIME = " elapsed time ";
181
182 public void print() {
183 System.out.println(toString());
184 }
185
186 @Override
187 public String toString() {
188 DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch);
189 return buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, "");
190 }
191
192 public void log() {
193 Marker profilerMarker = MarkerFactory.getMarker(PROFILER_MARKER_NAME);
194 if (logger == null) {
195 throw new NullPointerException("If you invoke the log() method, then you must associate a logger with this profiler.");
196 }
197 if (logger.isDebugEnabled(profilerMarker)) {
198 DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch);
199 String r = buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, "");
200 logger.debug(profilerMarker, SpacePadder.LINE_SEP + r);
201 }
202 }
203
204 /**
205 * Return a copy of the child instrument list for this Profiler instance.
206 *
207 * @return a copy of this instance's child time instrument list
208 * @since 1.5.9
209 */
210 public List<TimeInstrument> getCopyOfChildTimeInstruments() {
211 List<TimeInstrument> copy = new ArrayList<TimeInstrument>(childTimeInstrumentList);
212 return copy;
213 }
214
215 /**
216 * Return a copy of the global stopwatch of this Profiler instance.
217 *
218 * @return a copy of this instance's global stop watch
219 * @since 1.5.9
220 */
221 public StopWatch getCopyOfGlobalStopWatch() {
222 StopWatch copy = new StopWatch(globalStopWatch);
223 return copy;
224 }
225
226 private String buildProfilerString(DurationUnit du, String firstPrefix, String label, String indentation) {
227 StringBuilder buf = new StringBuilder();
228
229 buf.append(firstPrefix);
230 buf.append(" Profiler [");
231 buf.append(name);
232 buf.append("]");
233 buf.append(SpacePadder.LINE_SEP);
234 for (TimeInstrument child : childTimeInstrumentList) {
235 if (child instanceof StopWatch) {
236 buildStopWatchString(buf, du, ELAPSED_TIME, indentation, (StopWatch) child);
237 } else if (child instanceof Profiler) {
238 Profiler profiler = (Profiler) child;
239 String subString = profiler.buildProfilerString(du, NESTED_PROFILER_FIRST_PREFIX, SUBTOTAL_ELAPSED, indentation + " ");
240 buf.append(subString);
241 buildStopWatchString(buf, du, ELAPSED_TIME, indentation, profiler.globalStopWatch);
242 }
243 }
244 buildStopWatchString(buf, du, label, indentation, globalStopWatch);
245 return buf.toString();
246 }
247
248 private static void buildStopWatchString(StringBuilder buf, DurationUnit du, String prefix, String indentation, StopWatch sw) {
249
250 buf.append(indentation);
251 buf.append("|--");
252 buf.append(prefix);
253 SpacePadder.leftPad(buf, "[" + sw.getName() + "]", MIN_SW_NAME_LENGTH);
254 buf.append(" ");
255 String timeStr = Util.durationInDurationUnitsAsStr(sw.elapsedTime(), du);
256 SpacePadder.leftPad(buf, timeStr, MIN_SW_ELAPSED_TIME_NUMBER_LENGTH);
257 buf.append(" ");
258 Util.appendDurationUnitAsStr(buf, du);
259 buf.append(SpacePadder.LINE_SEP);
260 }
261 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.slf4j.Logger;
30 import org.slf4j.Marker;
31 import org.slf4j.MarkerFactory;
32
33 // + Profiler [BAS]
34 // |-- elapsed time [doX] 0 milliseconds.
35 // |-- elapsed time [doYYYYY] 56 milliseconds.
36 // |--+ Profiler Y
37 // |-- elapsed time [doZ] 21 milliseconds.
38 // |-- elapsed time [doZ] 21 milliseconds.
39 // |-- Total elapsed time [Y] 78 milliseconds.
40 // |-- elapsed time [doZ] 21 milliseconds.
41 // |-- Total elapsed time [BAS] 78 milliseconds.
42
43 /**
44 * A poor man's profiler to measure the time elapsed performing some lengthy
45 * task.
46 *
47 * @author Ceki G&uuml;lc&uuml;
48 */
49 public class Profiler implements TimeInstrument {
50
51 final static String PROFILER_MARKER_NAME = "PROFILER";
52
53 final static int MIN_SW_NAME_LENGTH = 24;
54 final static int MIN_SW_ELAPSED_TIME_NUMBER_LENGTH = 9;
55
56 final String name;
57 final StopWatch globalStopWatch;
58
59 List<TimeInstrument> childTimeInstrumentList = new ArrayList<TimeInstrument>();
60
61 // optional field
62 ProfilerRegistry profilerRegistry;
63 // optional field
64 Logger logger;
65
66 public Profiler(String name) {
67 this.name = name;
68 this.globalStopWatch = new StopWatch(name);
69 }
70
71 public String getName() {
72 return name;
73 }
74
75 public ProfilerRegistry getProfilerRegistry() {
76 return profilerRegistry;
77 }
78
79 public void registerWith(ProfilerRegistry profilerRegistry) {
80 if (profilerRegistry == null) {
81 return;
82 }
83 this.profilerRegistry = profilerRegistry;
84 profilerRegistry.put(this);
85 }
86
87 public Logger getLogger() {
88 return logger;
89 }
90
91 public void setLogger(Logger logger) {
92 this.logger = logger;
93 }
94
95 /**
96 * Starts a child stop watch and stops any previously started time
97 * instruments.
98 */
99 public void start(String name) {
100 stopLastTimeInstrument();
101 StopWatch childSW = new StopWatch(name);
102 childTimeInstrumentList.add(childSW);
103 }
104
105 public Profiler startNested(String name) {
106 stopLastTimeInstrument();
107 Profiler nestedProfiler = new Profiler(name);
108 nestedProfiler.registerWith(profilerRegistry);
109 nestedProfiler.setLogger(logger);
110 childTimeInstrumentList.add(nestedProfiler);
111 return nestedProfiler;
112 }
113
114 TimeInstrument getLastTimeInstrument() {
115 if (childTimeInstrumentList.size() > 0) {
116 return childTimeInstrumentList.get(childTimeInstrumentList.size() - 1);
117 } else {
118 return null;
119 }
120 }
121
122 void stopLastTimeInstrument() {
123 TimeInstrument last = getLastTimeInstrument();
124 if (last != null) {
125 last.stop();
126 }
127 }
128
129 // void stopNestedProfilers() {
130 // for (Object child : childTimeInstrumentList) {
131 // if (child instanceof Profiler)
132 // ((Profiler) child).stop();
133 // }
134 // }
135
136 public long elapsedTime() {
137 return globalStopWatch.elapsedTime();
138 }
139
140 public TimeInstrument stop() {
141 stopLastTimeInstrument();
142 globalStopWatch.stop();
143 return this;
144 }
145
146 public TimeInstrumentStatus getStatus() {
147 return globalStopWatch.status;
148 }
149
150 /**
151 * This method is used in tests.
152 */
153 void sanityCheck() throws IllegalStateException {
154 if (getStatus() != TimeInstrumentStatus.STOPPED) {
155 throw new IllegalStateException("time instrument [" + getName() + " is not stopped");
156 }
157
158 long totalElapsed = globalStopWatch.elapsedTime();
159 long childTotal = 0;
160
161 for (TimeInstrument ti : childTimeInstrumentList) {
162 childTotal += ti.elapsedTime();
163 if (ti.getStatus() != TimeInstrumentStatus.STOPPED) {
164 throw new IllegalStateException("time instrument [" + ti.getName() + " is not stopped");
165 }
166 if (ti instanceof Profiler) {
167 Profiler nestedProfiler = (Profiler) ti;
168 nestedProfiler.sanityCheck();
169 }
170 }
171 if (totalElapsed < childTotal) {
172 throw new IllegalStateException("children have a higher accumulated elapsed time");
173 }
174 }
175
176 static String TOP_PROFILER_FIRST_PREFIX = "+";
177 static String NESTED_PROFILER_FIRST_PREFIX = "|---+";
178 static String TOTAL_ELAPSED = " Total ";
179 static String SUBTOTAL_ELAPSED = " Subtotal ";
180 static String ELAPSED_TIME = " elapsed time ";
181
182 public void print() {
183 System.out.println(toString());
184 }
185
186 @Override
187 public String toString() {
188 DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch);
189 return buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, "");
190 }
191
192 public void log() {
193 Marker profilerMarker = MarkerFactory.getMarker(PROFILER_MARKER_NAME);
194 if (logger == null) {
195 throw new NullPointerException("If you invoke the log() method, then you must associate a logger with this profiler.");
196 }
197 if (logger.isDebugEnabled(profilerMarker)) {
198 DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch);
199 String r = buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, "");
200 logger.debug(profilerMarker, SpacePadder.LINE_SEP + r);
201 }
202 }
203
204 /**
205 * Return a copy of the child instrument list for this Profiler instance.
206 *
207 * @return a copy of this instance's child time instrument list
208 * @since 1.5.9
209 */
210 public List<TimeInstrument> getCopyOfChildTimeInstruments() {
211 List<TimeInstrument> copy = new ArrayList<TimeInstrument>(childTimeInstrumentList);
212 return copy;
213 }
214
215 /**
216 * Return a copy of the global stopwatch of this Profiler instance.
217 *
218 * @return a copy of this instance's global stop watch
219 * @since 1.5.9
220 */
221 public StopWatch getCopyOfGlobalStopWatch() {
222 StopWatch copy = new StopWatch(globalStopWatch);
223 return copy;
224 }
225
226 private String buildProfilerString(DurationUnit du, String firstPrefix, String label, String indentation) {
227 StringBuilder buf = new StringBuilder();
228
229 buf.append(firstPrefix);
230 buf.append(" Profiler [");
231 buf.append(name);
232 buf.append("]");
233 buf.append(SpacePadder.LINE_SEP);
234 for (TimeInstrument child : childTimeInstrumentList) {
235 if (child instanceof StopWatch) {
236 buildStopWatchString(buf, du, ELAPSED_TIME, indentation, (StopWatch) child);
237 } else if (child instanceof Profiler) {
238 Profiler profiler = (Profiler) child;
239 String subString = profiler.buildProfilerString(du, NESTED_PROFILER_FIRST_PREFIX, SUBTOTAL_ELAPSED, indentation + " ");
240 buf.append(subString);
241 buildStopWatchString(buf, du, ELAPSED_TIME, indentation, profiler.globalStopWatch);
242 }
243 }
244 buildStopWatchString(buf, du, label, indentation, globalStopWatch);
245 return buf.toString();
246 }
247
248 private static void buildStopWatchString(StringBuilder buf, DurationUnit du, String prefix, String indentation, StopWatch sw) {
249
250 buf.append(indentation);
251 buf.append("|--");
252 buf.append(prefix);
253 SpacePadder.leftPad(buf, "[" + sw.getName() + "]", MIN_SW_NAME_LENGTH);
254 buf.append(" ");
255 String timeStr = Util.durationInDurationUnitsAsStr(sw.elapsedTime(), du);
256 SpacePadder.leftPad(buf, timeStr, MIN_SW_ELAPSED_TIME_NUMBER_LENGTH);
257 buf.append(" ");
258 Util.appendDurationUnitAsStr(buf, du);
259 buf.append(SpacePadder.LINE_SEP);
260 }
261 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.HashMap;
27 import java.util.Map;
28
29 /**
30 * A minimalist registry of profilers.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class ProfilerRegistry {
35
36 private static final InheritableThreadLocal<ProfilerRegistry> inheritableThreadLocal = new InheritableThreadLocal<ProfilerRegistry>();
37
38 Map<String, Profiler> profilerMap = new HashMap<String, Profiler>();
39
40 public void put(Profiler profiler) {
41 put(profiler.getName(), profiler);
42 }
43
44 public void put(String name, Profiler profiler) {
45 profilerMap.put(name, profiler);
46 }
47
48 public static ProfilerRegistry getThreadContextInstance() {
49 ProfilerRegistry pr = inheritableThreadLocal.get();
50 if (pr == null) {
51 pr = new ProfilerRegistry();
52 inheritableThreadLocal.set(pr);
53 }
54 return pr;
55 }
56
57 public Profiler get(String name) {
58 return profilerMap.get(name);
59 }
60
61 public void clear() {
62 profilerMap.clear();
63 }
64 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.HashMap;
27 import java.util.Map;
28
29 /**
30 * A minimalist registry of profilers.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class ProfilerRegistry {
35
36 private static final InheritableThreadLocal<ProfilerRegistry> inheritableThreadLocal = new InheritableThreadLocal<ProfilerRegistry>();
37
38 Map<String, Profiler> profilerMap = new HashMap<String, Profiler>();
39
40 public void put(Profiler profiler) {
41 put(profiler.getName(), profiler);
42 }
43
44 public void put(String name, Profiler profiler) {
45 profilerMap.put(name, profiler);
46 }
47
48 public static ProfilerRegistry getThreadContextInstance() {
49 ProfilerRegistry pr = inheritableThreadLocal.get();
50 if (pr == null) {
51 pr = new ProfilerRegistry();
52 inheritableThreadLocal.set(pr);
53 }
54 return pr;
55 }
56
57 public Profiler get(String name) {
58 return profilerMap.get(name);
59 }
60
61 public void clear() {
62 profilerMap.clear();
63 }
64 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 public class SpacePadder {
27 public static final String LINE_SEP = System.getProperty("line.separator");
28
29 final static String[] SPACES = { " ", " ", " ", " ", // 1,2,4,8
30 // spaces
31 " ", // 16 spaces
32 " " }; // 32 spaces
33
34 @Deprecated
35 final static public void leftPad(StringBuffer buf, String s, int desiredLength) {
36 int actualLen = 0;
37 if (s != null) {
38 actualLen = s.length();
39 }
40 if (actualLen < desiredLength) {
41 spacePad(buf, desiredLength - actualLen);
42 }
43 if (s != null) {
44 buf.append(s);
45 }
46 }
47
48 final static public void leftPad(StringBuilder buf, String s, int desiredLength) {
49 int actualLen = 0;
50 if (s != null) {
51 actualLen = s.length();
52 }
53 if (actualLen < desiredLength) {
54 spacePad(buf, desiredLength - actualLen);
55 }
56 if (s != null) {
57 buf.append(s);
58 }
59 }
60
61 @Deprecated
62 final static public void rightPad(StringBuffer buf, String s, int desiredLength) {
63 int actualLen = 0;
64 if (s != null) {
65 actualLen = s.length();
66 }
67 if (s != null) {
68 buf.append(s);
69 }
70 if (actualLen < desiredLength) {
71 spacePad(buf, desiredLength - actualLen);
72 }
73 }
74
75 final static public void rightPad(StringBuilder buf, String s, int desiredLength) {
76 int actualLen = 0;
77 if (s != null) {
78 actualLen = s.length();
79 }
80 if (s != null) {
81 buf.append(s);
82 }
83 if (actualLen < desiredLength) {
84 spacePad(buf, desiredLength - actualLen);
85 }
86 }
87
88 /**
89 * Fast space padding method.
90 *
91 * @param sbuf the buffer to pad
92 * @param length the target size of the buffer after padding
93 */
94 @Deprecated
95 final static public void spacePad(StringBuffer sbuf, int length) {
96 while (length >= 32) {
97 sbuf.append(SPACES[5]);
98 length -= 32;
99 }
100
101 for (int i = 4; i >= 0; i--) {
102 if ((length & (1 << i)) != 0) {
103 sbuf.append(SPACES[i]);
104 }
105 }
106 }
107
108 /**
109 * Fast space padding method.
110 *
111 * @param sbuf the buffer to pad
112 * @param length the target size of the buffer after padding
113 */
114 final static public void spacePad(StringBuilder sbuf, int length) {
115 while (length >= 32) {
116 sbuf.append(SPACES[5]);
117 length -= 32;
118 }
119
120 for (int i = 4; i >= 0; i--) {
121 if ((length & (1 << i)) != 0) {
122 sbuf.append(SPACES[i]);
123 }
124 }
125 }
126 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 public class SpacePadder {
27 public static final String LINE_SEP = System.getProperty("line.separator");
28
29 final static String[] SPACES = { " ", " ", " ", " ", // 1,2,4,8
30 // spaces
31 " ", // 16 spaces
32 " " }; // 32 spaces
33
34 @Deprecated
35 final static public void leftPad(StringBuffer buf, String s, int desiredLength) {
36 int actualLen = 0;
37 if (s != null) {
38 actualLen = s.length();
39 }
40 if (actualLen < desiredLength) {
41 spacePad(buf, desiredLength - actualLen);
42 }
43 if (s != null) {
44 buf.append(s);
45 }
46 }
47
48 final static public void leftPad(StringBuilder buf, String s, int desiredLength) {
49 int actualLen = 0;
50 if (s != null) {
51 actualLen = s.length();
52 }
53 if (actualLen < desiredLength) {
54 spacePad(buf, desiredLength - actualLen);
55 }
56 if (s != null) {
57 buf.append(s);
58 }
59 }
60
61 @Deprecated
62 final static public void rightPad(StringBuffer buf, String s, int desiredLength) {
63 int actualLen = 0;
64 if (s != null) {
65 actualLen = s.length();
66 }
67 if (s != null) {
68 buf.append(s);
69 }
70 if (actualLen < desiredLength) {
71 spacePad(buf, desiredLength - actualLen);
72 }
73 }
74
75 final static public void rightPad(StringBuilder buf, String s, int desiredLength) {
76 int actualLen = 0;
77 if (s != null) {
78 actualLen = s.length();
79 }
80 if (s != null) {
81 buf.append(s);
82 }
83 if (actualLen < desiredLength) {
84 spacePad(buf, desiredLength - actualLen);
85 }
86 }
87
88 /**
89 * Fast space padding method.
90 *
91 * @param sbuf the buffer to pad
92 * @param length the target size of the buffer after padding
93 */
94 @Deprecated
95 final static public void spacePad(StringBuffer sbuf, int length) {
96 while (length >= 32) {
97 sbuf.append(SPACES[5]);
98 length -= 32;
99 }
100
101 for (int i = 4; i >= 0; i--) {
102 if ((length & (1 << i)) != 0) {
103 sbuf.append(SPACES[i]);
104 }
105 }
106 }
107
108 /**
109 * Fast space padding method.
110 *
111 * @param sbuf the buffer to pad
112 * @param length the target size of the buffer after padding
113 */
114 final static public void spacePad(StringBuilder sbuf, int length) {
115 while (length >= 32) {
116 sbuf.append(SPACES[5]);
117 length -= 32;
118 }
119
120 for (int i = 4; i >= 0; i--) {
121 if ((length & (1 << i)) != 0) {
122 sbuf.append(SPACES[i]);
123 }
124 }
125 }
126 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 * A very basic {@link TimeInstrument} which can be started and stopped
28 * once and only once.
29 *
30 * @author Ceki G&uuml;lc&uuml;
31 *
32 */
33 public class StopWatch implements TimeInstrument {
34
35 private String name;
36 private long startTime;
37 private long stopTime;
38 TimeInstrumentStatus status;
39
40 public StopWatch(String name) {
41 start(name);
42 }
43
44 StopWatch(StopWatch original) {
45 this.name = original.name;
46 this.startTime = original.startTime;
47 this.stopTime = original.stopTime;
48 this.status = original.status;
49 }
50
51 public void start(String name) {
52 this.name = name;
53 startTime = System.nanoTime();
54 status = TimeInstrumentStatus.STARTED;
55 }
56
57 public String getName() {
58 return name;
59 }
60
61 public TimeInstrument stop() {
62 if (status == TimeInstrumentStatus.STOPPED) {
63 return this;
64 }
65 return stop(System.nanoTime());
66 }
67
68 public StopWatch stop(long stopTime) {
69 this.status = TimeInstrumentStatus.STOPPED;
70 this.stopTime = stopTime;
71 return this;
72 }
73
74 @Override
75 public String toString() {
76 StringBuilder buf = new StringBuilder();
77 buf.append("StopWatch [");
78 buf.append(name);
79 buf.append("] ");
80
81 switch (status) {
82 case STARTED:
83 buf.append("STARTED");
84 break;
85 case STOPPED:
86 buf.append("elapsed time: ");
87 buf.append(Util.durationInDurationUnitsAsStr(elapsedTime(), DurationUnit.MICROSECOND));
88 break;
89 default:
90 throw new IllegalStateException("Status " + status + " is not expected");
91 }
92 return buf.toString();
93 }
94
95 public final long elapsedTime() {
96 if (status == TimeInstrumentStatus.STARTED) {
97 return 0;
98 } else {
99 return stopTime - startTime;
100 }
101 }
102
103 public TimeInstrumentStatus getStatus() {
104 return status;
105 }
106
107 public void print() {
108 System.out.println(toString());
109 }
110
111 public void log() {
112 throw new UnsupportedOperationException("A stopwatch instance does not know how to log");
113 }
114
115 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 * A very basic {@link TimeInstrument} which can be started and stopped
28 * once and only once.
29 *
30 * @author Ceki G&uuml;lc&uuml;
31 *
32 */
33 public class StopWatch implements TimeInstrument {
34
35 private String name;
36 private long startTime;
37 private long stopTime;
38 TimeInstrumentStatus status;
39
40 public StopWatch(String name) {
41 start(name);
42 }
43
44 StopWatch(StopWatch original) {
45 this.name = original.name;
46 this.startTime = original.startTime;
47 this.stopTime = original.stopTime;
48 this.status = original.status;
49 }
50
51 public void start(String name) {
52 this.name = name;
53 startTime = System.nanoTime();
54 status = TimeInstrumentStatus.STARTED;
55 }
56
57 public String getName() {
58 return name;
59 }
60
61 public TimeInstrument stop() {
62 if (status == TimeInstrumentStatus.STOPPED) {
63 return this;
64 }
65 return stop(System.nanoTime());
66 }
67
68 public StopWatch stop(long stopTime) {
69 this.status = TimeInstrumentStatus.STOPPED;
70 this.stopTime = stopTime;
71 return this;
72 }
73
74 @Override
75 public String toString() {
76 StringBuilder buf = new StringBuilder();
77 buf.append("StopWatch [");
78 buf.append(name);
79 buf.append("] ");
80
81 switch (status) {
82 case STARTED:
83 buf.append("STARTED");
84 break;
85 case STOPPED:
86 buf.append("elapsed time: ");
87 buf.append(Util.durationInDurationUnitsAsStr(elapsedTime(), DurationUnit.MICROSECOND));
88 break;
89 default:
90 throw new IllegalStateException("Status " + status + " is not expected");
91 }
92 return buf.toString();
93 }
94
95 public final long elapsedTime() {
96 if (status == TimeInstrumentStatus.STARTED) {
97 return 0;
98 } else {
99 return stopTime - startTime;
100 }
101 }
102
103 public TimeInstrumentStatus getStatus() {
104 return status;
105 }
106
107 public void print() {
108 System.out.println(toString());
109 }
110
111 public void log() {
112 throw new UnsupportedOperationException("A stopwatch instance does not know how to log");
113 }
114
115 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 * This interface sets the methods that must be implemented by
28 * {@link Profiler} and {@link StopWatch} classes. It settles the
29 * general feel of the profiler package.
30 *
31 * @author Ceki G&uuml;lc&uuml;
32 *
33 */
34 public interface TimeInstrument {
35
36 /**
37 * All time instruments are named entities.
38 * @return the name of this instrument
39 */
40 String getName();
41
42 TimeInstrumentStatus getStatus();
43
44 /**
45 * Start this time instrument.
46 *
47 * @param name
48 */
49 void start(String name);
50
51 /**
52 * Stop this time instrument.
53 *
54 * @return this
55 */
56 TimeInstrument stop();
57
58 /**
59 * Time elapsed between start and stop, in nanoseconds.
60 *
61 * @return time elapsed in nanoseconds
62 */
63 long elapsedTime();
64
65 /**
66 * Print information about this time instrument on the console.
67 */
68 void print();
69
70 /**
71 * If the time instrument has an associated logger, then log information about
72 * this time instrument. Note that {@link StopWatch} instances cannot log while {@link Profiler}
73 * instances can.
74 */
75 void log();
76 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 * This interface sets the methods that must be implemented by
28 * {@link Profiler} and {@link StopWatch} classes. It settles the
29 * general feel of the profiler package.
30 *
31 * @author Ceki G&uuml;lc&uuml;
32 *
33 */
34 public interface TimeInstrument {
35
36 /**
37 * All time instruments are named entities.
38 * @return the name of this instrument
39 */
40 String getName();
41
42 TimeInstrumentStatus getStatus();
43
44 /**
45 * Start this time instrument.
46 *
47 * @param name
48 */
49 void start(String name);
50
51 /**
52 * Stop this time instrument.
53 *
54 * @return this
55 */
56 TimeInstrument stop();
57
58 /**
59 * Time elapsed between start and stop, in nanoseconds.
60 *
61 * @return time elapsed in nanoseconds
62 */
63 long elapsedTime();
64
65 /**
66 * Print information about this time instrument on the console.
67 */
68 void print();
69
70 /**
71 * If the time instrument has an associated logger, then log information about
72 * this time instrument. Note that {@link StopWatch} instances cannot log while {@link Profiler}
73 * instances can.
74 */
75 void log();
76 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 /**
26 * A StopWatch can be in two states: STARTED or STOPPED.
27 */
28
29 package org.slf4j.profiler;
30
31 /**
32 * A time instrument can be in STARTED or STOPPED status.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 *
36 */
37 enum TimeInstrumentStatus {
38 STARTED, STOPPED;
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 /**
26 * A StopWatch can be in two states: STARTED or STOPPED.
27 */
28
29 package org.slf4j.profiler;
30
31 /**
32 * A time instrument can be in STARTED or STOPPED status.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 *
36 */
37 enum TimeInstrumentStatus {
38 STARTED, STOPPED;
3939 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.text.DecimalFormat;
27
28 /**
29 *
30 * A collection of utility methods.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 *
34 */
35 class Util {
36
37 static final long NANOS_IN_ONE_MICROSECOND = 1000;
38 static final long NANOS_IN_ONE_MILLISECOND = NANOS_IN_ONE_MICROSECOND * 1000;
39 static final long NANOS_IN_ONE_SECOND = NANOS_IN_ONE_MILLISECOND * 1000;
40 private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.000");
41
42 static DurationUnit selectDurationUnitForDisplay(StopWatch sw) {
43 return selectDurationUnitForDisplay(sw.elapsedTime());
44 }
45
46 static DurationUnit selectDurationUnitForDisplay(long durationInNanos) {
47 if (durationInNanos < 10 * NANOS_IN_ONE_MICROSECOND) {
48 return DurationUnit.NANOSECOND;
49 } else if (durationInNanos < 10 * NANOS_IN_ONE_MILLISECOND) {
50 return DurationUnit.MICROSECOND;
51 } else if (durationInNanos < 10 * NANOS_IN_ONE_SECOND) {
52 return DurationUnit.MILLISSECOND;
53 } else {
54 return DurationUnit.SECOND;
55 }
56 }
57
58 static public double convertToMicros(long nanos) {
59 return (double) nanos / NANOS_IN_ONE_MICROSECOND;
60 }
61
62 static public double convertToMillis(long nanos) {
63 return (double) nanos / NANOS_IN_ONE_MILLISECOND;
64 }
65
66 static public double convertToSeconds(long nanos) {
67 return ((double) nanos / NANOS_IN_ONE_SECOND);
68 }
69
70 static String durationInDurationUnitsAsStr(StringBuilder buf, StopWatch sw) {
71 DurationUnit du = selectDurationUnitForDisplay(sw);
72 return durationInDurationUnitsAsStr(sw.elapsedTime(), du);
73 }
74
75 static String durationInDurationUnitsAsStr(long nanos, DurationUnit durationUnit) {
76 StringBuilder buf = new StringBuilder();
77 switch (durationUnit) {
78 case NANOSECOND:
79 buf.append(nanos);
80 break;
81 case MICROSECOND:
82 double micros = convertToMicros(nanos);
83 buf.append(DECIMAL_FORMAT.format(micros));
84 break;
85 case MILLISSECOND:
86 double millis = convertToMillis(nanos);
87 buf.append(DECIMAL_FORMAT.format(millis));
88 break;
89 case SECOND:
90 double seconds = convertToSeconds(nanos);
91 buf.append(DECIMAL_FORMAT.format(seconds));
92 break;
93 }
94 return buf.toString();
95 }
96
97 static void appendDurationUnitAsStr(StringBuilder buf, DurationUnit durationUnit) {
98 switch (durationUnit) {
99 case NANOSECOND:
100 buf.append("nanoseconds.");
101 break;
102 case MICROSECOND:
103 buf.append("microseconds.");
104 break;
105 case MILLISSECOND:
106 buf.append("milliseconds.");
107 break;
108 case SECOND:
109 buf.append(" seconds.");
110 break;
111 }
112 }
113 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.text.DecimalFormat;
27
28 /**
29 *
30 * A collection of utility methods.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 *
34 */
35 class Util {
36
37 static final long NANOS_IN_ONE_MICROSECOND = 1000;
38 static final long NANOS_IN_ONE_MILLISECOND = NANOS_IN_ONE_MICROSECOND * 1000;
39 static final long NANOS_IN_ONE_SECOND = NANOS_IN_ONE_MILLISECOND * 1000;
40 private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.000");
41
42 static DurationUnit selectDurationUnitForDisplay(StopWatch sw) {
43 return selectDurationUnitForDisplay(sw.elapsedTime());
44 }
45
46 static DurationUnit selectDurationUnitForDisplay(long durationInNanos) {
47 if (durationInNanos < 10 * NANOS_IN_ONE_MICROSECOND) {
48 return DurationUnit.NANOSECOND;
49 } else if (durationInNanos < 10 * NANOS_IN_ONE_MILLISECOND) {
50 return DurationUnit.MICROSECOND;
51 } else if (durationInNanos < 10 * NANOS_IN_ONE_SECOND) {
52 return DurationUnit.MILLISSECOND;
53 } else {
54 return DurationUnit.SECOND;
55 }
56 }
57
58 static public double convertToMicros(long nanos) {
59 return (double) nanos / NANOS_IN_ONE_MICROSECOND;
60 }
61
62 static public double convertToMillis(long nanos) {
63 return (double) nanos / NANOS_IN_ONE_MILLISECOND;
64 }
65
66 static public double convertToSeconds(long nanos) {
67 return ((double) nanos / NANOS_IN_ONE_SECOND);
68 }
69
70 static String durationInDurationUnitsAsStr(StringBuilder buf, StopWatch sw) {
71 DurationUnit du = selectDurationUnitForDisplay(sw);
72 return durationInDurationUnitsAsStr(sw.elapsedTime(), du);
73 }
74
75 static String durationInDurationUnitsAsStr(long nanos, DurationUnit durationUnit) {
76 StringBuilder buf = new StringBuilder();
77 switch (durationUnit) {
78 case NANOSECOND:
79 buf.append(nanos);
80 break;
81 case MICROSECOND:
82 double micros = convertToMicros(nanos);
83 buf.append(DECIMAL_FORMAT.format(micros));
84 break;
85 case MILLISSECOND:
86 double millis = convertToMillis(nanos);
87 buf.append(DECIMAL_FORMAT.format(millis));
88 break;
89 case SECOND:
90 double seconds = convertToSeconds(nanos);
91 buf.append(DECIMAL_FORMAT.format(seconds));
92 break;
93 }
94 return buf.toString();
95 }
96
97 static void appendDurationUnitAsStr(StringBuilder buf, DurationUnit durationUnit) {
98 switch (durationUnit) {
99 case NANOSECOND:
100 buf.append("nanoseconds.");
101 break;
102 case MICROSECOND:
103 buf.append("microseconds.");
104 break;
105 case MILLISSECOND:
106 buf.append("milliseconds.");
107 break;
108 case SECOND:
109 buf.append(" seconds.");
110 break;
111 }
112 }
113 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9
10 <p>Poor man's profiler API</p>
11 </body>
12 </html>
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9
10 <p>Poor man's profiler API</p>
11 </body>
12 </html>
0 Implementation-Title: slf4j-ext
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.ext
3 Bundle-Name: slf4j-ext
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.profiler;version=${parsedVersion.osgiVersion}, org.slf4j.cal10n;version=${parsedVersion.osgiVersion}, org.slf4j.ext;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, ch.qos.cal10n;version=${cal10n.version}
0 Implementation-Title: slf4j-ext
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.ext
3 Bundle-Name: slf4j-ext
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.profiler;version=${parsedVersion.osgiVersion}, org.slf4j.cal10n;version=${parsedVersion.osgiVersion}, org.slf4j.ext;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, ch.qos.cal10n;version=${cal10n.version}
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Before;
29 import org.junit.Test;
30
31 public class NDCTest {
32
33 @Before
34 public void setUp() throws Exception {
35 MDC.clear();
36 }
37
38 @Test
39 public void testEmpty() {
40 assertEquals("", NDC.pop());
41 }
42
43 @Test
44 public void testSmoke() {
45 NDC.push("a");
46 String result = NDC.pop();
47 assertEquals("a", result);
48 }
49
50 @Test
51 public void testSmoke2() {
52 NDC.push("a");
53 NDC.push("b");
54 String result1 = NDC.pop();
55 String result0 = NDC.pop();
56 assertEquals("b", result1);
57 assertEquals("a", result0);
58 }
59 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Before;
29 import org.junit.Test;
30
31 public class NDCTest {
32
33 @Before
34 public void setUp() throws Exception {
35 MDC.clear();
36 }
37
38 @Test
39 public void testEmpty() {
40 assertEquals("", NDC.pop());
41 }
42
43 @Test
44 public void testSmoke() {
45 NDC.push("a");
46 String result = NDC.pop();
47 assertEquals("a", result);
48 }
49
50 @Test
51 public void testSmoke2() {
52 NDC.push("a");
53 NDC.push("b");
54 String result1 = NDC.pop();
55 String result0 = NDC.pop();
56 assertEquals("b", result1);
57 assertEquals("a", result0);
58 }
59 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.util.Locale;
29
30 import org.apache.log4j.spi.LoggingEvent;
31 import org.junit.Before;
32 import org.junit.Test;
33 import org.slf4j.cal10n.LocLogger;
34 import org.slf4j.cal10n.LocLoggerFactory;
35 import org.slf4j.dummyExt.ListAppender;
36
37 import ch.qos.cal10n.IMessageConveyor;
38 import ch.qos.cal10n.MessageConveyor;
39
40 public class LocLoggerTest {
41
42 ListAppender listAppender;
43 org.apache.log4j.Logger log4jRoot;
44
45 IMessageConveyor imc = new MessageConveyor(Locale.UK);
46 LocLoggerFactory llFactory_uk = new LocLoggerFactory(imc);
47
48 final static String EXPECTED_FILE_NAME = "LocLoggerTest.java";
49
50 @Before
51 public void setUp() throws Exception {
52 // start from a clean slate for each test
53
54 listAppender = new ListAppender();
55 listAppender.extractLocationInfo = true;
56 log4jRoot = org.apache.log4j.Logger.getRootLogger();
57 log4jRoot.addAppender(listAppender);
58 log4jRoot.setLevel(org.apache.log4j.Level.TRACE);
59 }
60
61 void verify(LoggingEvent le, String expectedMsg) {
62 assertEquals(expectedMsg, le.getMessage());
63 assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName());
64 }
65
66 @Test
67 public void testSmoke() {
68 LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass());
69 locLogger.info(Months.JAN);
70 verify((LoggingEvent) listAppender.list.get(0), "January");
71
72 }
73 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.util.Locale;
29
30 import org.apache.log4j.spi.LoggingEvent;
31 import org.junit.Before;
32 import org.junit.Test;
33 import org.slf4j.cal10n.LocLogger;
34 import org.slf4j.cal10n.LocLoggerFactory;
35 import org.slf4j.dummyExt.ListAppender;
36
37 import ch.qos.cal10n.IMessageConveyor;
38 import ch.qos.cal10n.MessageConveyor;
39
40 public class LocLoggerTest {
41
42 ListAppender listAppender;
43 org.apache.log4j.Logger log4jRoot;
44
45 IMessageConveyor imc = new MessageConveyor(Locale.UK);
46 LocLoggerFactory llFactory_uk = new LocLoggerFactory(imc);
47
48 final static String EXPECTED_FILE_NAME = "LocLoggerTest.java";
49
50 @Before
51 public void setUp() throws Exception {
52 // start from a clean slate for each test
53
54 listAppender = new ListAppender();
55 listAppender.extractLocationInfo = true;
56 log4jRoot = org.apache.log4j.Logger.getRootLogger();
57 log4jRoot.addAppender(listAppender);
58 log4jRoot.setLevel(org.apache.log4j.Level.TRACE);
59 }
60
61 void verify(LoggingEvent le, String expectedMsg) {
62 assertEquals(expectedMsg, le.getMessage());
63 assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName());
64 }
65
66 @Test
67 public void testSmoke() {
68 LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass());
69 locLogger.info(Months.JAN);
70 verify((LoggingEvent) listAppender.list.get(0), "January");
71
72 }
73 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import ch.qos.cal10n.BaseName;
27 import ch.qos.cal10n.Locale;
28 import ch.qos.cal10n.LocaleData;
29
30 @BaseName("months")
31 @LocaleData(@Locale("en"))
32 public enum Months {
33 JAN, FEB, MAR, APR, MAY, JUN;
34 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import ch.qos.cal10n.BaseName;
27 import ch.qos.cal10n.Locale;
28 import ch.qos.cal10n.LocaleData;
29
30 @BaseName("months")
31 @LocaleData(@Locale("en"))
32 public enum Months {
33 JAN, FEB, MAR, APR, MAY, JUN;
34 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import java.util.Locale;
27
28 import org.slf4j.cal10n.LocLogger;
29 import org.slf4j.cal10n.LocLoggerFactory;
30
31 import ch.qos.cal10n.IMessageConveyor;
32 import ch.qos.cal10n.MessageConveyor;
33
34 public class MyApplication {
35
36 // create a message conveyor for a given locale
37 IMessageConveyor messageConveyor = new MessageConveyor(Locale.JAPAN);
38
39 // create the LogLoggerFactory
40 LocLoggerFactory llFactory_uk = new LocLoggerFactory(messageConveyor);
41
42 // create a locLogger
43 LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass());
44
45 public void applicationStart() {
46 locLogger.info(Production.APPLICATION_STARTED);
47 // ..
48 }
49
50 public void applicationStop() {
51 locLogger.info(Production.APPLICATION_STOPPED);
52 // ...
53 }
54 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import java.util.Locale;
27
28 import org.slf4j.cal10n.LocLogger;
29 import org.slf4j.cal10n.LocLoggerFactory;
30
31 import ch.qos.cal10n.IMessageConveyor;
32 import ch.qos.cal10n.MessageConveyor;
33
34 public class MyApplication {
35
36 // create a message conveyor for a given locale
37 IMessageConveyor messageConveyor = new MessageConveyor(Locale.JAPAN);
38
39 // create the LogLoggerFactory
40 LocLoggerFactory llFactory_uk = new LocLoggerFactory(messageConveyor);
41
42 // create a locLogger
43 LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass());
44
45 public void applicationStart() {
46 locLogger.info(Production.APPLICATION_STARTED);
47 // ..
48 }
49
50 public void applicationStop() {
51 locLogger.info(Production.APPLICATION_STOPPED);
52 // ...
53 }
54 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ LocLoggerTest.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ LocLoggerTest.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import ch.qos.cal10n.LocaleData;
27 import ch.qos.cal10n.Locale;
28 import ch.qos.cal10n.BaseName;
29
30 @BaseName("production")
31 @LocaleData({ @Locale("en_UK"), @Locale("fr") })
32 public enum Production {
33 APPLICATION_STARTED, APPLICATION_STOPPED, DB_CONNECTION, DB_CONNECTION_FAILURE;
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import ch.qos.cal10n.LocaleData;
27 import ch.qos.cal10n.Locale;
28 import ch.qos.cal10n.BaseName;
29
30 @BaseName("production")
31 @LocaleData({ @Locale("en_UK"), @Locale("fr") })
32 public enum Production {
33 APPLICATION_STARTED, APPLICATION_STOPPED, DB_CONNECTION, DB_CONNECTION_FAILURE;
3434 }
+0
-106
slf4j-ext/src/test/java/org/slf4j/dummyExt/EventLoggerTest.java less more
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.util.Date;
29 import java.util.Locale;
30 import java.util.TimeZone;
31
32 import org.apache.log4j.spi.LocationInfo;
33 import org.apache.log4j.spi.LoggingEvent;
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.slf4j.MDC;
38 import org.slf4j.ext.EventData;
39 import org.slf4j.ext.EventLogger;
40
41 public class EventLoggerTest {
42
43 ListAppender listAppender;
44 org.apache.log4j.Logger log4;
45
46 final static String EXPECTED_FILE_NAME = "EventLoggerTest.java";
47
48 @Before
49 public void setUp() throws Exception {
50
51 // start from a clean slate for each test
52
53 listAppender = new ListAppender();
54 listAppender.extractLocationInfo = true;
55 org.apache.log4j.Logger eventLogger = org.apache.log4j.Logger.getLogger("EventLogger");
56 eventLogger.addAppender(listAppender);
57 eventLogger.setLevel(org.apache.log4j.Level.TRACE);
58 eventLogger.setAdditivity(false);
59 // Items that apply to any activity
60 MDC.put("ipAddress", "192.168.1.110");
61 MDC.put("login", "TestUSer");
62 MDC.put("hostname", "localhost");
63 MDC.put("productName", "SLF4J");
64 MDC.put("locale", Locale.getDefault().getDisplayName());
65 MDC.put("timezone", TimeZone.getDefault().getDisplayName());
66
67 }
68
69 @After
70 public void tearDown() throws Exception {
71 MDC.clear();
72 }
73
74 void verify(LoggingEvent le, String expectedMsg) {
75 assertEquals(expectedMsg, le.getMessage());
76 assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName());
77 }
78
79 @Test
80 public void testEventLogger() {
81 EventData data[] = new EventData[2];
82 data[0] = new EventData();
83 data[0].setEventType("Login");
84 data[0].setEventId("1");
85 data[0].setEventDateTime(new Date());
86 data[0].put("Userid", "TestUser");
87 EventLogger.logEvent(data[0]);
88
89 data[1] = new EventData();
90 data[1].setEventType("Update");
91 data[1].setEventId("2");
92 data[1].setEventDateTime(new Date());
93 data[1].put("FileName", "/etc/hosts");
94 EventLogger.logEvent(data[1]);
95
96 assertEquals(2, listAppender.list.size());
97 for (int i = 0; i < 2; ++i) {
98 LoggingEvent event = listAppender.list.get(i);
99 verify(event, data[i].toXML());
100 LocationInfo li = event.getLocationInformation();
101 assertEquals(this.getClass().getName(), li.getClassName());
102 assertEquals(event.getMDC("hostname"), "localhost");
103 }
104 }
105 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.apache.log4j.AppenderSkeleton;
30 import org.apache.log4j.spi.LoggingEvent;
31
32 public class ListAppender extends AppenderSkeleton {
33
34 public List<LoggingEvent> list = new ArrayList<LoggingEvent>();
35
36 public boolean extractLocationInfo = false;
37
38 protected void append(LoggingEvent event) {
39 list.add(event);
40 if (extractLocationInfo) {
41 event.getLocationInformation();
42 }
43 }
44
45 public void close() {
46 }
47
48 public boolean requiresLayout() {
49 return false;
50 }
51
52 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.apache.log4j.AppenderSkeleton;
30 import org.apache.log4j.spi.LoggingEvent;
31
32 public class ListAppender extends AppenderSkeleton {
33
34 public List<LoggingEvent> list = new ArrayList<LoggingEvent>();
35
36 public boolean extractLocationInfo = false;
37
38 protected void append(LoggingEvent event) {
39 list.add(event);
40 if (extractLocationInfo) {
41 event.getLocationInformation();
42 }
43 }
44
45 public void close() {
46 }
47
48 public boolean requiresLayout() {
49 return false;
50 }
51
52 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29 import org.slf4j.MDC;
30 import org.slf4j.ext.MDCStrLookup;
31
32 public class MDCStrLookupTest {
33
34 @Test
35 public void testLookup() throws Exception {
36 MDC.put("key", "value");
37 MDC.put("number", "2");
38 MDCStrLookup lookup = new MDCStrLookup();
39 assertEquals("value", lookup.lookup("key"));
40 assertEquals("2", lookup.lookup("number"));
41 assertEquals(null, lookup.lookup(null));
42 assertEquals(null, lookup.lookup(""));
43 assertEquals(null, lookup.lookup("other"));
44 }
45 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29 import org.slf4j.MDC;
30 import org.slf4j.ext.MDCStrLookup;
31
32 public class MDCStrLookupTest {
33
34 @Test
35 public void testLookup() throws Exception {
36 MDC.put("key", "value");
37 MDC.put("number", "2");
38 MDCStrLookup lookup = new MDCStrLookup();
39 assertEquals("value", lookup.lookup("key"));
40 assertEquals("2", lookup.lookup("number"));
41 assertEquals(null, lookup.lookup(null));
42 assertEquals(null, lookup.lookup(""));
43 assertEquals(null, lookup.lookup("other"));
44 }
45 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ MDCStrLookupTest.class, XLoggerTest.class, EventLoggerTest.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ MDCStrLookupTest.class, XLoggerTest.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.apache.log4j.spi.LocationInfo;
29 import org.apache.log4j.spi.LoggingEvent;
30 import org.junit.Before;
31 import org.junit.Test;
32 import org.slf4j.ext.XLogger;
33 import org.slf4j.ext.XLoggerFactory;
34
35 public class XLoggerTest {
36
37 ListAppender listAppender;
38 org.apache.log4j.Logger log4jRoot;
39
40 final static String EXPECTED_FILE_NAME = "XLoggerTest.java";
41
42 @Before
43 public void setUp() throws Exception {
44
45 // start from a clean slate for each test
46
47 listAppender = new ListAppender();
48 listAppender.extractLocationInfo = true;
49 log4jRoot = org.apache.log4j.Logger.getRootLogger();
50 log4jRoot.addAppender(listAppender);
51 log4jRoot.setLevel(org.apache.log4j.Level.TRACE);
52 }
53
54 void verify(LoggingEvent le, String expectedMsg) {
55 assertEquals(expectedMsg, le.getMessage());
56 assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName());
57 }
58
59 void verifyWithException(LoggingEvent le, String expectedMsg, Throwable t) {
60 verify(le, expectedMsg);
61 assertEquals(t.toString(), le.getThrowableStrRep()[0]);
62 }
63
64 void verifyWithLevelAndException(LoggingEvent le, XLogger.Level level, String expectedMsg, Throwable t) {
65 verify(le, expectedMsg);
66 assertEquals(t.toString(), le.getThrowableStrRep()[0]);
67 assertEquals(le.getLevel().toString(), level.toString());
68 }
69
70 @Test
71 public void testEntering() {
72 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
73 logger.entry();
74 logger.entry(1);
75 logger.entry("test");
76 logger.entry("a", "b", "c", "d");
77 logger.entry("a", "b", "c", "d", "e");
78 logger.entry("a", "b", "c", "d", "e", "f");
79
80 assertEquals(6, listAppender.list.size());
81 verify((LoggingEvent) listAppender.list.get(0), "entry");
82 verify((LoggingEvent) listAppender.list.get(1), "entry with (1)");
83 verify((LoggingEvent) listAppender.list.get(2), "entry with (test)");
84 }
85
86 @Test
87 public void testExiting() {
88 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
89 logger.exit();
90 assertEquals(Integer.valueOf(0), logger.exit(0));
91 assertEquals(Boolean.FALSE, logger.exit(false));
92
93 assertEquals(3, listAppender.list.size());
94 verify((LoggingEvent) listAppender.list.get(0), "exit");
95 verify((LoggingEvent) listAppender.list.get(1), "exit with (0)");
96 verify((LoggingEvent) listAppender.list.get(2), "exit with (false)");
97 }
98
99 @Test
100 public void testThrowing() {
101 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
102 Throwable t = new UnsupportedOperationException("Test");
103 assertEquals(t, logger.throwing(t));
104 assertEquals(t, logger.throwing(XLogger.Level.DEBUG, t));
105 assertEquals(2, listAppender.list.size());
106 verifyWithException((LoggingEvent) listAppender.list.get(0), "throwing", t);
107 LoggingEvent event = (LoggingEvent) listAppender.list.get(1);
108 verifyWithLevelAndException(event, XLogger.Level.DEBUG, "throwing", t);
109 }
110
111 @Test
112 public void testCaught() {
113 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
114 long x = 5;
115 Throwable t = null;
116 try {
117 @SuppressWarnings("unused")
118 long y = x / 0;
119 } catch (Exception ex) {
120 t = ex;
121 logger.catching(ex);
122 logger.catching(XLogger.Level.DEBUG, ex);
123 }
124 verifyWithException((LoggingEvent) listAppender.list.get(0), "catching", t);
125 verifyWithLevelAndException((LoggingEvent) listAppender.list.get(1), XLogger.Level.DEBUG, "catching", t);
126 }
127
128 // See http://jira.qos.ch/browse/SLF4J-105
129 // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=114
130 @Test
131 public void testLocationExtraction_Bug114() {
132 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
133 int line = 135; // requires update if line numbers change
134 logger.exit();
135 logger.debug("hello");
136
137 assertEquals(2, listAppender.list.size());
138
139 {
140 LoggingEvent e = listAppender.list.get(0);
141 LocationInfo li = e.getLocationInformation();
142 assertEquals(this.getClass().getName(), li.getClassName());
143 assertEquals("" + line, li.getLineNumber());
144 }
145
146 {
147 LoggingEvent e = listAppender.list.get(1);
148 LocationInfo li = e.getLocationInformation();
149 assertEquals(this.getClass().getName(), li.getClassName());
150 assertEquals("" + (line + 1), li.getLineNumber());
151 }
152
153 }
154 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.apache.log4j.spi.LocationInfo;
29 import org.apache.log4j.spi.LoggingEvent;
30 import org.junit.Before;
31 import org.junit.Test;
32 import org.slf4j.ext.XLogger;
33 import org.slf4j.ext.XLoggerFactory;
34
35 public class XLoggerTest {
36
37 ListAppender listAppender;
38 org.apache.log4j.Logger log4jRoot;
39
40 final static String EXPECTED_FILE_NAME = "XLoggerTest.java";
41
42 @Before
43 public void setUp() throws Exception {
44
45 // start from a clean slate for each test
46
47 listAppender = new ListAppender();
48 listAppender.extractLocationInfo = true;
49 log4jRoot = org.apache.log4j.Logger.getRootLogger();
50 log4jRoot.addAppender(listAppender);
51 log4jRoot.setLevel(org.apache.log4j.Level.TRACE);
52 }
53
54 void verify(LoggingEvent le, String expectedMsg) {
55 assertEquals(expectedMsg, le.getMessage());
56 assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName());
57 }
58
59 void verifyWithException(LoggingEvent le, String expectedMsg, Throwable t) {
60 verify(le, expectedMsg);
61 assertEquals(t.toString(), le.getThrowableStrRep()[0]);
62 }
63
64 void verifyWithLevelAndException(LoggingEvent le, XLogger.Level level, String expectedMsg, Throwable t) {
65 verify(le, expectedMsg);
66 assertEquals(t.toString(), le.getThrowableStrRep()[0]);
67 assertEquals(le.getLevel().toString(), level.toString());
68 }
69
70 @Test
71 public void testEntering() {
72 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
73 logger.entry();
74 logger.entry(1);
75 logger.entry("test");
76 logger.entry("a", "b", "c", "d");
77 logger.entry("a", "b", "c", "d", "e");
78 logger.entry("a", "b", "c", "d", "e", "f");
79
80 assertEquals(6, listAppender.list.size());
81 verify((LoggingEvent) listAppender.list.get(0), "entry");
82 verify((LoggingEvent) listAppender.list.get(1), "entry with (1)");
83 verify((LoggingEvent) listAppender.list.get(2), "entry with (test)");
84 }
85
86 @Test
87 public void testExiting() {
88 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
89 logger.exit();
90 assertEquals(Integer.valueOf(0), logger.exit(0));
91 assertEquals(Boolean.FALSE, logger.exit(false));
92
93 assertEquals(3, listAppender.list.size());
94 verify((LoggingEvent) listAppender.list.get(0), "exit");
95 verify((LoggingEvent) listAppender.list.get(1), "exit with (0)");
96 verify((LoggingEvent) listAppender.list.get(2), "exit with (false)");
97 }
98
99 @Test
100 public void testThrowing() {
101 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
102 Throwable t = new UnsupportedOperationException("Test");
103 assertEquals(t, logger.throwing(t));
104 assertEquals(t, logger.throwing(XLogger.Level.DEBUG, t));
105 assertEquals(2, listAppender.list.size());
106 verifyWithException((LoggingEvent) listAppender.list.get(0), "throwing", t);
107 LoggingEvent event = (LoggingEvent) listAppender.list.get(1);
108 verifyWithLevelAndException(event, XLogger.Level.DEBUG, "throwing", t);
109 }
110
111 @Test
112 public void testCaught() {
113 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
114 long x = 5;
115 Throwable t = null;
116 try {
117 @SuppressWarnings("unused")
118 long y = x / 0;
119 } catch (Exception ex) {
120 t = ex;
121 logger.catching(ex);
122 logger.catching(XLogger.Level.DEBUG, ex);
123 }
124 verifyWithException((LoggingEvent) listAppender.list.get(0), "catching", t);
125 verifyWithLevelAndException((LoggingEvent) listAppender.list.get(1), XLogger.Level.DEBUG, "catching", t);
126 }
127
128 // See http://jira.qos.ch/browse/SLF4J-105
129 // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=114
130 @Test
131 public void testLocationExtraction_Bug114() {
132 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
133 int line = 135; // requires update if line numbers change
134 logger.exit();
135 logger.debug("hello");
136
137 assertEquals(2, listAppender.list.size());
138
139 {
140 LoggingEvent e = listAppender.list.get(0);
141 LocationInfo li = e.getLocationInformation();
142 assertEquals(this.getClass().getName(), li.getClassName());
143 assertEquals("" + line, li.getLineNumber());
144 }
145
146 {
147 LoggingEvent e = listAppender.list.get(1);
148 LocationInfo li = e.getLocationInformation();
149 assertEquals(this.getClass().getName(), li.getClassName());
150 assertEquals("" + (line + 1), li.getLineNumber());
151 }
152
153 }
154 }
0 <html>
1 <body>
2 Tests related to the org.slf4j.ext package. However, location information code
3 required the caller class (XLogger) to have a different prefix than
4 the test class XLoggerTest. This is ensured by having the test class
5 placed in a different package.
6 </body>
0 <html>
1 <body>
2 Tests related to the org.slf4j.ext package. However, location information code
3 required the caller class (XLogger) to have a different prefix than
4 the test class XLoggerTest. This is ensured by having the test class
5 placed in a different package.
6 </body>
77 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.instrumentation;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29
30 public class ToStringHelperTest {
31
32 @Test
33 public void testRenderer() {
34 assertEquals("", "null", ToStringHelper.render(null));
35 assertEquals("", "a", ToStringHelper.render("a"));
36 assertEquals("", "[]", ToStringHelper.render(new String[0]));
37
38 assertEquals("", "[a]", ToStringHelper.render(new String[] { "a" }));
39
40 assertEquals("", "[a, b]", ToStringHelper.render(new String[] { "a", "b" }));
41
42 assertEquals("", "[a, b, c]", ToStringHelper.render(new String[] { "a", "b", "c" }));
43
44 assertEquals("", "[[a], [b, c]]", ToStringHelper.render(new String[][] { { "a" }, { "b", "c" } }));
45
46 assertEquals("", "[0, [a], [b, c]]", ToStringHelper.render(new Object[] { "0", new String[] { "a" }, new Object[] { "b", "c" } }));
47
48 assertEquals("", "[1]", ToStringHelper.render(new int[] { 1 }));
49
50 assertEquals("", "[1, 2, 3]", ToStringHelper.render(new int[] { 1, 2, 3 }));
51
52 assertEquals("", "[1, 2, 3]", ToStringHelper.render(new long[] { 1, 2, 3 }));
53
54 assertEquals("", "[1, 2, 3]", ToStringHelper.render(new short[] { 1, 2, 3 }));
55
56 assertEquals("", "[[1, 2], [], [3, 4]]", ToStringHelper.render(new byte[][] { { 1, 2 }, {}, { 3, 4 } }));
57
58 assertEquals("", "[1.0, 2.0, 3.0]", ToStringHelper.render(new float[] { 1, 2, 3 }));
59
60 assertEquals("", "[1.0, 2.0, 3.0]", ToStringHelper.render(new double[] { 1, 2, 3 }));
61
62 assertEquals("", "[[1.0, 2.0, 3.0]]", ToStringHelper.render(new double[][] { { 1, 2, 3 } }));
63
64 assertEquals("", "[true, false, true]", ToStringHelper.render(new boolean[] { true, false, true }));
65 }
66
67 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.instrumentation;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29
30 public class ToStringHelperTest {
31
32 @Test
33 public void testRenderer() {
34 assertEquals("", "null", ToStringHelper.render(null));
35 assertEquals("", "a", ToStringHelper.render("a"));
36 assertEquals("", "[]", ToStringHelper.render(new String[0]));
37
38 assertEquals("", "[a]", ToStringHelper.render(new String[] { "a" }));
39
40 assertEquals("", "[a, b]", ToStringHelper.render(new String[] { "a", "b" }));
41
42 assertEquals("", "[a, b, c]", ToStringHelper.render(new String[] { "a", "b", "c" }));
43
44 assertEquals("", "[[a], [b, c]]", ToStringHelper.render(new String[][] { { "a" }, { "b", "c" } }));
45
46 assertEquals("", "[0, [a], [b, c]]", ToStringHelper.render(new Object[] { "0", new String[] { "a" }, new Object[] { "b", "c" } }));
47
48 assertEquals("", "[1]", ToStringHelper.render(new int[] { 1 }));
49
50 assertEquals("", "[1, 2, 3]", ToStringHelper.render(new int[] { 1, 2, 3 }));
51
52 assertEquals("", "[1, 2, 3]", ToStringHelper.render(new long[] { 1, 2, 3 }));
53
54 assertEquals("", "[1, 2, 3]", ToStringHelper.render(new short[] { 1, 2, 3 }));
55
56 assertEquals("", "[[1, 2], [], [3, 4]]", ToStringHelper.render(new byte[][] { { 1, 2 }, {}, { 3, 4 } }));
57
58 assertEquals("", "[1.0, 2.0, 3.0]", ToStringHelper.render(new float[] { 1, 2, 3 }));
59
60 assertEquals("", "[1.0, 2.0, 3.0]", ToStringHelper.render(new double[] { 1, 2, 3 }));
61
62 assertEquals("", "[[1.0, 2.0, 3.0]]", ToStringHelper.render(new double[][] { { 1, 2, 3 } }));
63
64 assertEquals("", "[true, false, true]", ToStringHelper.render(new boolean[] { true, false, true }));
65 }
66
67 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 *
28 * This demo illustrates usage of SLF4J profilers.
29 *
30 * <p>
31 * We have been given the task of generating a large number, say N, of random
32 * integers. We need to transform that array into a smaller array containing
33 * only prime numbers. The new array has to be sorted.
34 *
35 * <p>
36 * While tackling this problem, we would like to measure the time spent in each
37 * subtask.
38 *
39 * <p>
40 * A typical output for this demo would be:
41 *
42 * <pre>
43 + Profiler [BASIC]
44 |-- elapsed time [A] 213.186 milliseconds.
45 |-- elapsed time [B] 2499.107 milliseconds.
46 |-- elapsed time [OTHER] 3300.752 milliseconds.
47 |-- Total [BASIC] 6014.161 milliseconds.
48 </pre>
49 *
50 * @author Ceki Gulcu
51 */
52 public class BasicProfilerDemo {
53
54 public static void main(String[] args) {
55 // create a profiler called "BASIC"
56 Profiler profiler = new Profiler("BASIC");
57 profiler.start("A");
58 doA();
59
60 profiler.start("B");
61 doB();
62
63 profiler.start("OTHER");
64 doOther();
65 profiler.stop().print();
66 }
67
68 static private void doA() {
69 delay(200);
70 }
71
72 static private void doB() {
73 delay(2500);
74 }
75
76 static private void doOther() {
77 delay(3300);
78 }
79
80 static private void delay(int millis) {
81 try {
82 Thread.sleep(millis);
83 } catch (InterruptedException e) {
84 }
85 }
86 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 *
28 * This demo illustrates usage of SLF4J profilers.
29 *
30 * <p>
31 * We have been given the task of generating a large number, say N, of random
32 * integers. We need to transform that array into a smaller array containing
33 * only prime numbers. The new array has to be sorted.
34 *
35 * <p>
36 * While tackling this problem, we would like to measure the time spent in each
37 * subtask.
38 *
39 * <p>
40 * A typical output for this demo would be:
41 *
42 * <pre>
43 + Profiler [BASIC]
44 |-- elapsed time [A] 213.186 milliseconds.
45 |-- elapsed time [B] 2499.107 milliseconds.
46 |-- elapsed time [OTHER] 3300.752 milliseconds.
47 |-- Total [BASIC] 6014.161 milliseconds.
48 </pre>
49 *
50 * @author Ceki Gulcu
51 */
52 public class BasicProfilerDemo {
53
54 public static void main(String[] args) {
55 // create a profiler called "BASIC"
56 Profiler profiler = new Profiler("BASIC");
57 profiler.start("A");
58 doA();
59
60 profiler.start("B");
61 doB();
62
63 profiler.start("OTHER");
64 doOther();
65 profiler.stop().print();
66 }
67
68 static private void doA() {
69 delay(200);
70 }
71
72 static private void doB() {
73 delay(2500);
74 }
75
76 static private void doOther() {
77 delay(3300);
78 }
79
80 static private void delay(int millis) {
81 try {
82 Thread.sleep(millis);
83 } catch (InterruptedException e) {
84 }
85 }
86 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 *
28 * This demo illustrates usage of SLF4J profilers.
29 *
30 * <p>
31 * We have been given the task of generating a large number, say N,
32 * of random integers. We need to transform that array into a smaller array
33 * containing only prime numbers. The new array has to be sorted.
34 *
35 * <p>
36 * While tackling this problem, we would like to measure the
37 * time spent in each subtask.
38 *
39 * <p>
40 * A typical output for this demo would be:
41 <pre>
42 + Profiler [DEMO]
43 |-- elapsed time [RANDOM] 0.089 seconds.
44 |---+ Profiler [SORT_AND_PRUNE]
45 &nbsp;&nbsp;&nbsp;&nbsp;|-- elapsed time [SORT] 0.221 seconds.
46 &nbsp;&nbsp;&nbsp;&nbsp;|-- elapsed time [PRUNE_COMPOSITES] 11.567 seconds.
47 &nbsp;&nbsp;&nbsp;&nbsp;|-- Subtotal [SORT_AND_PRUNE] 11.788 seconds.
48 |-- elapsed time [SORT_AND_PRUNE] 11.788 seconds.
49 |-- Total [DEMO] 11.877 seconds.
50 </pre>
51 *
52 * @author Ceki Gulcu
53 */
54 public class NestedProfilerDemo {
55
56 public static void main(String[] args) {
57 // create a profiler called "DEMO"
58 Profiler profiler = new Profiler("DEMO");
59
60 // register this profiler in the thread context's profiler registry
61 ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance();
62 profiler.registerWith(profilerRegistry);
63
64 // start a stopwatch called "RANDOM"
65 profiler.start("RANDOM");
66 RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator();
67 int n = 10 * 1000;
68 int[] randomArray = riaGenerator.generate(n);
69
70 // create and start a nested profiler called "SORT_AND_PRUNE"
71 // By virtue of its parent-child relationship with the "DEMO"
72 // profiler, and the previous registration of the parent profiler,
73 // this nested profiler will be automatically registered
74 // with the thread context's profiler registry
75 profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME);
76
77 SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray);
78 pruner.sortAndPruneComposites();
79
80 // stop and print the "DEMO" printer
81 profiler.stop().print();
82 }
83 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 *
28 * This demo illustrates usage of SLF4J profilers.
29 *
30 * <p>
31 * We have been given the task of generating a large number, say N,
32 * of random integers. We need to transform that array into a smaller array
33 * containing only prime numbers. The new array has to be sorted.
34 *
35 * <p>
36 * While tackling this problem, we would like to measure the
37 * time spent in each subtask.
38 *
39 * <p>
40 * A typical output for this demo would be:
41 <pre>
42 + Profiler [DEMO]
43 |-- elapsed time [RANDOM] 0.089 seconds.
44 |---+ Profiler [SORT_AND_PRUNE]
45 &nbsp;&nbsp;&nbsp;&nbsp;|-- elapsed time [SORT] 0.221 seconds.
46 &nbsp;&nbsp;&nbsp;&nbsp;|-- elapsed time [PRUNE_COMPOSITES] 11.567 seconds.
47 &nbsp;&nbsp;&nbsp;&nbsp;|-- Subtotal [SORT_AND_PRUNE] 11.788 seconds.
48 |-- elapsed time [SORT_AND_PRUNE] 11.788 seconds.
49 |-- Total [DEMO] 11.877 seconds.
50 </pre>
51 *
52 * @author Ceki Gulcu
53 */
54 public class NestedProfilerDemo {
55
56 public static void main(String[] args) {
57 // create a profiler called "DEMO"
58 Profiler profiler = new Profiler("DEMO");
59
60 // register this profiler in the thread context's profiler registry
61 ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance();
62 profiler.registerWith(profilerRegistry);
63
64 // start a stopwatch called "RANDOM"
65 profiler.start("RANDOM");
66 RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator();
67 int n = 10 * 1000;
68 int[] randomArray = riaGenerator.generate(n);
69
70 // create and start a nested profiler called "SORT_AND_PRUNE"
71 // By virtue of its parent-child relationship with the "DEMO"
72 // profiler, and the previous registration of the parent profiler,
73 // this nested profiler will be automatically registered
74 // with the thread context's profiler registry
75 profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME);
76
77 SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray);
78 pruner.sortAndPruneComposites();
79
80 // stop and print the "DEMO" printer
81 profiler.stop().print();
82 }
83 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 /**
30 *
31 * This demo illustrates usage of SLF4J profilers. It is almost identical to
32 * the first NestProfilerDemo, except that it uses a logger instead of
33 * printing its output on the console.
34 *
35
36 * @author Ceki Gulcu
37 */
38 public class NestedProfilerDemo2 {
39
40 static Logger logger = LoggerFactory.getLogger(NestedProfilerDemo2.class);
41
42 public static void main(String[] args) {
43 Profiler profiler = new Profiler("DEMO");
44 // associate a logger with the profiler
45 profiler.setLogger(logger);
46
47 ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance();
48 profiler.registerWith(profilerRegistry);
49
50 profiler.start("RANDOM");
51 RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator();
52 int n = 10 * 1000;
53 int[] randomArray = riaGenerator.generate(n);
54
55 profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME);
56
57 SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray);
58 pruner.sortAndPruneComposites();
59
60 // stop and log
61 profiler.stop().log();
62 }
63 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 /**
30 *
31 * This demo illustrates usage of SLF4J profilers. It is almost identical to
32 * the first NestProfilerDemo, except that it uses a logger instead of
33 * printing its output on the console.
34 *
35
36 * @author Ceki Gulcu
37 */
38 public class NestedProfilerDemo2 {
39
40 static Logger logger = LoggerFactory.getLogger(NestedProfilerDemo2.class);
41
42 public static void main(String[] args) {
43 Profiler profiler = new Profiler("DEMO");
44 // associate a logger with the profiler
45 profiler.setLogger(logger);
46
47 ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance();
48 profiler.registerWith(profilerRegistry);
49
50 profiler.start("RANDOM");
51 RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator();
52 int n = 10 * 1000;
53 int[] randomArray = riaGenerator.generate(n);
54
55 profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME);
56
57 SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray);
58 pruner.sortAndPruneComposites();
59
60 // stop and log
61 profiler.stop().log();
62 }
63 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ UtilTest.class, ProfilerTest.class })
32 public class PackageTest {
33
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ UtilTest.class, ProfilerTest.class })
32 public class PackageTest {
33
3434 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertNull;
29
30 import org.junit.Test;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 public class ProfilerTest {
35
36 Logger logger = LoggerFactory.getLogger(ProfilerTest.class);
37
38 @Test
39 public void testSmoke() {
40 Profiler profiler = new Profiler("SMOKE");
41 profiler.stop();
42 StopWatch gSW = profiler.globalStopWatch;
43
44 // verify
45 profiler.sanityCheck();
46 assertEquals(TimeInstrumentStatus.STOPPED, gSW.status);
47 assertEquals(0, profiler.childTimeInstrumentList.size());
48 assertNull(profiler.getLastTimeInstrument());
49 }
50
51 @Test
52 public void testBasicProfiling() {
53 Profiler profiler = new Profiler("BAS");
54
55 profiler.start("doX");
56 doX(1);
57
58 profiler.start("doY");
59 doY(10);
60
61 profiler.start("doZ");
62 doZ(2);
63 profiler.stop();
64
65 // verify
66 profiler.sanityCheck();
67 StopWatch gSW = profiler.globalStopWatch;
68 assertEquals(TimeInstrumentStatus.STOPPED, gSW.status);
69 assertEquals(3, profiler.childTimeInstrumentList.size());
70 assertNotNull(profiler.getLastTimeInstrument());
71 assertEquals("doZ", profiler.getLastTimeInstrument().getName());
72 }
73
74 // + Profiler [BAS]
75 // |-- elapsed time [doX] 1.272 milliseconds.
76 // |-- elapsed time [doYYYYY] 25.398 milliseconds.
77 // |--+ Profiler [subtask]
78 // |-- elapsed time [n1] 1.434 milliseconds.
79 // |-- elapsed time [n2] 5.855 milliseconds.
80 // |-- Total elapsed time [subtask] 7.321 milliseconds.
81 // |-- elapsed time [doZ] 3.211 milliseconds.
82 // |-- Total elapsed time [BAS] 30.317 milliseconds.
83 @Test
84 public void testNestedProfiling() {
85
86 Profiler profiler = new Profiler("BAS");
87 profiler.setLogger(logger);
88 profiler.start("doX");
89 doX(1);
90
91 profiler.start("doYYYYY");
92 for (int i = 0; i < 5; i++) {
93 doY(i);
94 }
95 Profiler nested = profiler.startNested("subtask");
96 doSubtask(nested);
97 profiler.start("doZ");
98 doZ(2);
99 profiler.stop();
100
101 // verify
102 profiler.sanityCheck();
103 StopWatch gSW = profiler.globalStopWatch;
104 assertEquals(TimeInstrumentStatus.STOPPED, gSW.status);
105 // assertEquals(3, profiler.stopwatchList.size());
106 assertEquals(4, profiler.childTimeInstrumentList.size());
107 assertNotNull(profiler.getLastTimeInstrument());
108 assertEquals("doZ", profiler.getLastTimeInstrument().getName());
109
110 }
111
112 private void doX(int millis) {
113 delay(millis);
114 }
115
116 private void doY(int millis) {
117 delay(millis);
118 }
119
120 private void doZ(int millis) {
121 delay(millis);
122 }
123
124 public void doSubtask(Profiler nested) {
125 nested.start("n1");
126 doX(1);
127
128 nested.start("n2");
129 doX(5);
130 nested.stop();
131 }
132
133 void delay(int millis) {
134 try {
135 Thread.sleep(millis);
136 } catch (InterruptedException e) {
137 }
138 }
139 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertNull;
29
30 import org.junit.Test;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 public class ProfilerTest {
35
36 Logger logger = LoggerFactory.getLogger(ProfilerTest.class);
37
38 @Test
39 public void testSmoke() {
40 Profiler profiler = new Profiler("SMOKE");
41 profiler.stop();
42 StopWatch gSW = profiler.globalStopWatch;
43
44 // verify
45 profiler.sanityCheck();
46 assertEquals(TimeInstrumentStatus.STOPPED, gSW.status);
47 assertEquals(0, profiler.childTimeInstrumentList.size());
48 assertNull(profiler.getLastTimeInstrument());
49 }
50
51 @Test
52 public void testBasicProfiling() {
53 Profiler profiler = new Profiler("BAS");
54
55 profiler.start("doX");
56 doX(1);
57
58 profiler.start("doY");
59 doY(10);
60
61 profiler.start("doZ");
62 doZ(2);
63 profiler.stop();
64
65 // verify
66 profiler.sanityCheck();
67 StopWatch gSW = profiler.globalStopWatch;
68 assertEquals(TimeInstrumentStatus.STOPPED, gSW.status);
69 assertEquals(3, profiler.childTimeInstrumentList.size());
70 assertNotNull(profiler.getLastTimeInstrument());
71 assertEquals("doZ", profiler.getLastTimeInstrument().getName());
72 }
73
74 // + Profiler [BAS]
75 // |-- elapsed time [doX] 1.272 milliseconds.
76 // |-- elapsed time [doYYYYY] 25.398 milliseconds.
77 // |--+ Profiler [subtask]
78 // |-- elapsed time [n1] 1.434 milliseconds.
79 // |-- elapsed time [n2] 5.855 milliseconds.
80 // |-- Total elapsed time [subtask] 7.321 milliseconds.
81 // |-- elapsed time [doZ] 3.211 milliseconds.
82 // |-- Total elapsed time [BAS] 30.317 milliseconds.
83 @Test
84 public void testNestedProfiling() {
85
86 Profiler profiler = new Profiler("BAS");
87 profiler.setLogger(logger);
88 profiler.start("doX");
89 doX(1);
90
91 profiler.start("doYYYYY");
92 for (int i = 0; i < 5; i++) {
93 doY(i);
94 }
95 Profiler nested = profiler.startNested("subtask");
96 doSubtask(nested);
97 profiler.start("doZ");
98 doZ(2);
99 profiler.stop();
100
101 // verify
102 profiler.sanityCheck();
103 StopWatch gSW = profiler.globalStopWatch;
104 assertEquals(TimeInstrumentStatus.STOPPED, gSW.status);
105 // assertEquals(3, profiler.stopwatchList.size());
106 assertEquals(4, profiler.childTimeInstrumentList.size());
107 assertNotNull(profiler.getLastTimeInstrument());
108 assertEquals("doZ", profiler.getLastTimeInstrument().getName());
109
110 }
111
112 private void doX(int millis) {
113 delay(millis);
114 }
115
116 private void doY(int millis) {
117 delay(millis);
118 }
119
120 private void doZ(int millis) {
121 delay(millis);
122 }
123
124 public void doSubtask(Profiler nested) {
125 nested.start("n1");
126 doX(1);
127
128 nested.start("n2");
129 doX(5);
130 nested.stop();
131 }
132
133 void delay(int millis) {
134 try {
135 Thread.sleep(millis);
136 } catch (InterruptedException e) {
137 }
138 }
139 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.Random;
27
28 public class RandomIntegerArrayGenerator {
29 Random rand = new Random(11);
30
31 int[] generate(int size) {
32 int[] result = new int[size];
33 for (int i = 0; i < size; i++) {
34 int r = rand.nextInt();
35 result[i] = r;
36 }
37 return result;
38 }
39 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.Random;
27
28 public class RandomIntegerArrayGenerator {
29 Random rand = new Random(11);
30
31 int[] generate(int size) {
32 int[] result = new int[size];
33 for (int i = 0; i < size; i++) {
34 int r = rand.nextInt();
35 result[i] = r;
36 }
37 return result;
38 }
39 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.ArrayList;
27 import java.util.Arrays;
28
29 public class SortAndPruneComposites {
30
31 static String NESTED_PROFILER_NAME = "SORT_AND_PRUNE";
32
33 final int[] originalArray;
34 final int originalArrrayLength;
35
36 public SortAndPruneComposites(int[] randomArray) {
37 this.originalArray = randomArray;
38 this.originalArrrayLength = randomArray.length;
39
40 }
41
42 public int[] sortAndPruneComposites() {
43 // retrieve previously registered profiler named "SORT_AND_PRUNE"
44 ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance();
45 Profiler sortProfiler = profilerRegistry.get(NESTED_PROFILER_NAME);
46
47 // start a new stopwatch called SORT
48 sortProfiler.start("SORT");
49 int[] sortedArray = sort();
50 // start a new stopwatch called PRUNE_COMPOSITES
51 sortProfiler.start("PRUNE_COMPOSITES");
52 int result[] = pruneComposites(sortedArray);
53
54 return result;
55 }
56
57 private int[] sort() {
58 int[] sortedArray = new int[originalArrrayLength];
59 System.arraycopy(originalArray, 0, sortedArray, 0, originalArrrayLength);
60 Arrays.sort(sortedArray);
61 return sortedArray;
62 }
63
64 int[] pruneComposites(int[] sortedArray) {
65 ArrayList<Integer> primesArray = new ArrayList<Integer>();
66 for (int i = 0; i < originalArrrayLength; i++) {
67 int n = sortedArray[i];
68 if (isPrime(n)) {
69 primesArray.add(n);
70 }
71 }
72 int resultSize = primesArray.size();
73 int[] result = new int[resultSize];
74
75 for (int i = 0; i < resultSize; i++) {
76 result[i] = primesArray.get(i);
77 }
78 return result;
79 }
80
81 public boolean isPrime(int n) {
82 if (n < 2) {
83 return false;
84 }
85 if (n % 2 == 0) {
86 return false;
87 }
88 for (int i = 3; i * i <= n; i += 2) {
89 if (n % i == 0) {
90 return false;
91 }
92 }
93 return true;
94 }
95 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.ArrayList;
27 import java.util.Arrays;
28
29 public class SortAndPruneComposites {
30
31 static String NESTED_PROFILER_NAME = "SORT_AND_PRUNE";
32
33 final int[] originalArray;
34 final int originalArrrayLength;
35
36 public SortAndPruneComposites(int[] randomArray) {
37 this.originalArray = randomArray;
38 this.originalArrrayLength = randomArray.length;
39
40 }
41
42 public int[] sortAndPruneComposites() {
43 // retrieve previously registered profiler named "SORT_AND_PRUNE"
44 ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance();
45 Profiler sortProfiler = profilerRegistry.get(NESTED_PROFILER_NAME);
46
47 // start a new stopwatch called SORT
48 sortProfiler.start("SORT");
49 int[] sortedArray = sort();
50 // start a new stopwatch called PRUNE_COMPOSITES
51 sortProfiler.start("PRUNE_COMPOSITES");
52 int result[] = pruneComposites(sortedArray);
53
54 return result;
55 }
56
57 private int[] sort() {
58 int[] sortedArray = new int[originalArrrayLength];
59 System.arraycopy(originalArray, 0, sortedArray, 0, originalArrrayLength);
60 Arrays.sort(sortedArray);
61 return sortedArray;
62 }
63
64 int[] pruneComposites(int[] sortedArray) {
65 ArrayList<Integer> primesArray = new ArrayList<Integer>();
66 for (int i = 0; i < originalArrrayLength; i++) {
67 int n = sortedArray[i];
68 if (isPrime(n)) {
69 primesArray.add(n);
70 }
71 }
72 int resultSize = primesArray.size();
73 int[] result = new int[resultSize];
74
75 for (int i = 0; i < resultSize; i++) {
76 result[i] = primesArray.get(i);
77 }
78 return result;
79 }
80
81 public boolean isPrime(int n) {
82 if (n < 2) {
83 return false;
84 }
85 if (n % 2 == 0) {
86 return false;
87 }
88 for (int i = 3; i * i <= n; i += 2) {
89 if (n % i == 0) {
90 return false;
91 }
92 }
93 return true;
94 }
95 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29
30 public class UtilTest {
31
32 @Test
33 public void testSelectDurationUnitForDisplay() throws InterruptedException {
34 assertEquals(DurationUnit.NANOSECOND, Util.selectDurationUnitForDisplay(10));
35 assertEquals(DurationUnit.NANOSECOND, Util.selectDurationUnitForDisplay(9 * Util.NANOS_IN_ONE_MICROSECOND));
36 assertEquals(DurationUnit.MICROSECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_MICROSECOND));
37 assertEquals(DurationUnit.MICROSECOND, Util.selectDurationUnitForDisplay(9 * Util.NANOS_IN_ONE_MILLISECOND));
38 assertEquals(DurationUnit.MILLISSECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_MILLISECOND));
39 assertEquals(DurationUnit.SECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_SECOND));
40 }
41
42 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29
30 public class UtilTest {
31
32 @Test
33 public void testSelectDurationUnitForDisplay() throws InterruptedException {
34 assertEquals(DurationUnit.NANOSECOND, Util.selectDurationUnitForDisplay(10));
35 assertEquals(DurationUnit.NANOSECOND, Util.selectDurationUnitForDisplay(9 * Util.NANOS_IN_ONE_MICROSECOND));
36 assertEquals(DurationUnit.MICROSECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_MICROSECOND));
37 assertEquals(DurationUnit.MICROSECOND, Util.selectDurationUnitForDisplay(9 * Util.NANOS_IN_ONE_MILLISECOND));
38 assertEquals(DurationUnit.MILLISSECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_MILLISECOND));
39 assertEquals(DurationUnit.SECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_SECOND));
40 }
41
42 }
0
1 log4j.rootLogger=DEBUG, CONSOLE
2
3 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
4 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
5 log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
0
1 log4j.rootLogger=DEBUG, CONSOLE
2
3 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
4 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
5 log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
0 JAN=January
1 FEB=February
2 MAR=March
3 APR=April
4 MAY=May
5 JUN=June
0 JAN=January
1 FEB=February
2 MAR=March
3 APR=April
4 MAY=May
5 JUN=June
0 APPLICATION_STARTED=APPLICATION_STARTED
1 APPLICATION_STOPPED=APPLICATION_STOPPED
2 DB_CONNECTION=DB_CONNECTION
0 APPLICATION_STARTED=APPLICATION_STARTED
1 APPLICATION_STOPPED=APPLICATION_STOPPED
2 DB_CONNECTION=DB_CONNECTION
33 DB_CONNECTION_FAILURE=DB_CONNECTION_FAILURE
0 APPLICATION_STARTED=APPLICATION_STARTED
1 APPLICATION_STOPPED=APPLICATION_STOPPED
2 DB_CONNECTION=DB_CONNECTION
0 APPLICATION_STARTED=APPLICATION_STARTED
1 APPLICATION_STOPPED=APPLICATION_STOPPED
2 DB_CONNECTION=DB_CONNECTION
33 DB_CONNECTION_FAILURE=DB_CONNECTION_FAILURE
0 Copyright (c) 2004-2007 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>slf4j-jcl</artifactId>
13 <packaging>jar</packaging>
14 <name>SLF4J JCL Binding</name>
15 <description>SLF4J JCL Binding</description>
16
17 <url>http://www.slf4j.org</url>
18
19 <dependencies>
20 <dependency>
21 <groupId>org.slf4j</groupId>
22 <artifactId>slf4j-api</artifactId>
23 </dependency>
24 <dependency>
25 <groupId>commons-logging</groupId>
26 <artifactId>commons-logging</artifactId>
27 <version>1.1.1</version>
28 </dependency>
29 </dependencies>
30
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>slf4j-jcl</artifactId>
13 <packaging>jar</packaging>
14 <name>SLF4J JCL Binding</name>
15 <description>SLF4J JCL Binding</description>
16
17 <url>http://www.slf4j.org</url>
18
19 <dependencies>
20 <dependency>
21 <groupId>org.slf4j</groupId>
22 <artifactId>slf4j-api</artifactId>
23 </dependency>
24 <dependency>
25 <groupId>commons-logging</groupId>
26 <artifactId>commons-logging</artifactId>
27 <version>1.1.1</version>
28 </dependency>
29 </dependencies>
30
3131 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j.impl;
26
27 import org.apache.commons.logging.Log;
28 import org.slf4j.Logger;
29 import org.slf4j.helpers.FormattingTuple;
30 import org.slf4j.helpers.MarkerIgnoringBase;
31 import org.slf4j.helpers.MessageFormatter;
32
33 /**
34 * A wrapper over {@link org.apache.commons.logging.Log
35 * org.apache.commons.logging.Log} in conformance with the {@link Logger}
36 * interface.
37 *
38 * @author Ceki G&uuml;lc&uuml;
39 */
40 public final class JCLLoggerAdapter extends MarkerIgnoringBase {
41
42 private static final long serialVersionUID = 4141593417490482209L;
43 final Log log;
44
45 // WARN: JCLLoggerAdapter constructor should have only package access so
46 // that only JCLLoggerFactory be able to create one.
47 JCLLoggerAdapter(Log log, String name) {
48 this.log = log;
49 this.name = name;
50 }
51
52 /**
53 * Delegates to the {@link Log#isTraceEnabled} method of the underlying
54 * {@link Log} instance.
55 */
56 public boolean isTraceEnabled() {
57 return log.isTraceEnabled();
58 }
59
60 //
61
62 /**
63 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
64 * {@link Log} instance.
65 *
66 * @param msg - the message object to be logged
67 */
68 public void trace(String msg) {
69 log.trace(msg);
70 }
71
72 /**
73 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
74 * {@link Log} instance.
75 *
76 * <p>
77 * However, this form avoids superfluous object creation when the logger is disabled
78 * for level TRACE.
79 * </p>
80 *
81 * @param format
82 * the format string
83 * @param arg
84 * the argument
85 */
86 public void trace(String format, Object arg) {
87 if (log.isTraceEnabled()) {
88 FormattingTuple ft = MessageFormatter.format(format, arg);
89 log.trace(ft.getMessage(), ft.getThrowable());
90 }
91 }
92
93 /**
94 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
95 * {@link Log} instance.
96 *
97 * <p>
98 * However, this form avoids superfluous object creation when the logger is disabled
99 * for level TRACE.
100 * </p>
101 *
102 * @param format
103 * the format string
104 * @param arg1
105 * the first argument
106 * @param arg2
107 * the second argument
108 */
109 public void trace(String format, Object arg1, Object arg2) {
110 if (log.isTraceEnabled()) {
111 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
112 log.trace(ft.getMessage(), ft.getThrowable());
113 }
114 }
115
116 /**
117 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
118 * {@link Log} instance.
119 *
120 * <p>
121 * However, this form avoids superfluous object creation when the logger is disabled
122 * for level TRACE.
123 * </p>
124 *
125 * @param format the format string
126 * @param arguments a list of 3 or more arguments
127 */
128 public void trace(String format, Object... arguments) {
129 if (log.isTraceEnabled()) {
130 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
131 log.trace(ft.getMessage(), ft.getThrowable());
132 }
133 }
134
135 /**
136 * Delegates to the {@link Log#trace(java.lang.Object, java.lang.Throwable)} method of
137 * the underlying {@link Log} instance.
138 *
139 * @param msg
140 * the message accompanying the exception
141 * @param t
142 * the exception (throwable) to log
143 */
144 public void trace(String msg, Throwable t) {
145 log.trace(msg, t);
146 }
147
148 /**
149 * Delegates to the {@link Log#isDebugEnabled} method of the underlying
150 * {@link Log} instance.
151 */
152 public boolean isDebugEnabled() {
153 return log.isDebugEnabled();
154 }
155
156 //
157
158 /**
159 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
160 * {@link Log} instance.
161 *
162 * @param msg - the message object to be logged
163 */
164 public void debug(String msg) {
165 log.debug(msg);
166 }
167
168 /**
169 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
170 * {@link Log} instance.
171 *
172 * <p>
173 * However, this form avoids superfluous object creation when the logger is disabled
174 * for level DEBUG.
175 * </p>
176 *
177 * @param format
178 * the format string
179 * @param arg
180 * the argument
181 */
182 public void debug(String format, Object arg) {
183 if (log.isDebugEnabled()) {
184 FormattingTuple ft = MessageFormatter.format(format, arg);
185 log.debug(ft.getMessage(), ft.getThrowable());
186 }
187 }
188
189 /**
190 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
191 * {@link Log} instance.
192 *
193 * <p>
194 * However, this form avoids superfluous object creation when the logger is disabled
195 * for level DEBUG.
196 * </p>
197 *
198 * @param format
199 * the format string
200 * @param arg1
201 * the first argument
202 * @param arg2
203 * the second argument
204 */
205 public void debug(String format, Object arg1, Object arg2) {
206 if (log.isDebugEnabled()) {
207 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
208 log.debug(ft.getMessage(), ft.getThrowable());
209 }
210 }
211
212 /**
213 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
214 * {@link Log} instance.
215 *
216 * <p>
217 * However, this form avoids superfluous object creation when the logger is disabled
218 * for level DEBUG.
219 * </p>
220 *
221 * @param format the format string
222 * @param arguments a list of 3 or more arguments
223 */
224 public void debug(String format, Object... arguments) {
225 if (log.isDebugEnabled()) {
226 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
227 log.debug(ft.getMessage(), ft.getThrowable());
228 }
229 }
230
231 /**
232 * Delegates to the {@link Log#debug(java.lang.Object, java.lang.Throwable)} method of
233 * the underlying {@link Log} instance.
234 *
235 * @param msg
236 * the message accompanying the exception
237 * @param t
238 * the exception (throwable) to log
239 */
240 public void debug(String msg, Throwable t) {
241 log.debug(msg, t);
242 }
243
244 /**
245 * Delegates to the {@link Log#isInfoEnabled} method of the underlying
246 * {@link Log} instance.
247 */
248 public boolean isInfoEnabled() {
249 return log.isInfoEnabled();
250 }
251
252 /**
253 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
254 * {@link Log} instance.
255 *
256 * @param msg - the message object to be logged
257 */
258 public void info(String msg) {
259 log.info(msg);
260 }
261
262 /**
263 * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying
264 * {@link Log} instance.
265 *
266 * <p>
267 * However, this form avoids superfluous object creation when the logger is disabled
268 * for level INFO.
269 * </p>
270 *
271 * @param format
272 * the format string
273 * @param arg
274 * the argument
275 */
276
277 public void info(String format, Object arg) {
278 if (log.isInfoEnabled()) {
279 FormattingTuple ft = MessageFormatter.format(format, arg);
280 log.info(ft.getMessage(), ft.getThrowable());
281 }
282 }
283
284 /**
285 * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying
286 * {@link Log} instance.
287 *
288 * <p>
289 * However, this form avoids superfluous object creation when the logger is disabled
290 * for level INFO.
291 * </p>
292 *
293 * @param format
294 * the format string
295 * @param arg1
296 * the first argument
297 * @param arg2
298 * the second argument
299 */
300 public void info(String format, Object arg1, Object arg2) {
301 if (log.isInfoEnabled()) {
302
303 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
304 log.info(ft.getMessage(), ft.getThrowable());
305 }
306 }
307
308 /**
309 * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying
310 * {@link Log} instance.
311 *
312 * <p>
313 * However, this form avoids superfluous object creation when the logger is disabled
314 * for level INFO.
315 * </p>
316 *
317 * @param format the format string
318 * @param arguments a list of 3 or more arguments
319 */
320 public void info(String format, Object... arguments) {
321 if (log.isInfoEnabled()) {
322 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
323 log.info(ft.getMessage(), ft.getThrowable());
324 }
325 }
326
327 /**
328 * Delegates to the {@link Log#info(java.lang.Object, java.lang.Throwable)} method of
329 * the underlying {@link Log} instance.
330 *
331 * @param msg
332 * the message accompanying the exception
333 * @param t
334 * the exception (throwable) to log
335 */
336 public void info(String msg, Throwable t) {
337 log.info(msg, t);
338 }
339
340 /**
341 * Delegates to the {@link Log#isWarnEnabled} method of the underlying
342 * {@link Log} instance.
343 */
344 public boolean isWarnEnabled() {
345 return log.isWarnEnabled();
346 }
347
348 /**
349 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
350 * {@link Log} instance.
351 *
352 * @param msg - the message object to be logged
353 */
354 public void warn(String msg) {
355 log.warn(msg);
356 }
357
358 /**
359 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
360 * {@link Log} instance.
361 *
362 * <p>
363 * However, this form avoids superfluous object creation when the logger is disabled
364 * for level WARN.
365 * </p>
366 *
367 * @param format
368 * the format string
369 * @param arg
370 * the argument
371 */
372 public void warn(String format, Object arg) {
373 if (log.isWarnEnabled()) {
374 FormattingTuple ft = MessageFormatter.format(format, arg);
375 log.warn(ft.getMessage(), ft.getThrowable());
376 }
377 }
378
379 /**
380 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
381 * {@link Log} instance.
382 *
383 * <p>
384 * However, this form avoids superfluous object creation when the logger is disabled
385 * for level WARN.
386 * </p>
387 *
388 * @param format
389 * the format string
390 * @param arg1
391 * the first argument
392 * @param arg2
393 * the second argument
394 */
395 public void warn(String format, Object arg1, Object arg2) {
396 if (log.isWarnEnabled()) {
397 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
398 log.warn(ft.getMessage(), ft.getThrowable());
399 }
400 }
401
402 /**
403 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
404 * {@link Log} instance.
405 *
406 * <p>
407 * However, this form avoids superfluous object creation when the logger is disabled
408 * for level WARN.
409 * </p>
410 *
411 * @param format the format string
412 * @param arguments a list of 3 or more arguments
413 */
414 public void warn(String format, Object... arguments) {
415 if (log.isWarnEnabled()) {
416 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
417 log.warn(ft.getMessage(), ft.getThrowable());
418 }
419 }
420
421 /**
422 * Delegates to the {@link Log#warn(java.lang.Object, java.lang.Throwable)} method of
423 * the underlying {@link Log} instance.
424 *
425 * @param msg
426 * the message accompanying the exception
427 * @param t
428 * the exception (throwable) to log
429 */
430
431 public void warn(String msg, Throwable t) {
432 log.warn(msg, t);
433 }
434
435 /**
436 * Delegates to the {@link Log#isErrorEnabled} method of the underlying
437 * {@link Log} instance.
438 */
439 public boolean isErrorEnabled() {
440 return log.isErrorEnabled();
441 }
442
443 /**
444 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
445 * {@link Log} instance.
446 *
447 * @param msg - the message object to be logged
448 */
449 public void error(String msg) {
450 log.error(msg);
451 }
452
453 /**
454 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
455 * {@link Log} instance.
456 *
457 * <p>
458 * However, this form avoids superfluous object creation when the logger is disabled
459 * for level ERROR.
460 * </p>
461 *
462 * @param format
463 * the format string
464 * @param arg
465 * the argument
466 */
467 public void error(String format, Object arg) {
468 if (log.isErrorEnabled()) {
469 FormattingTuple ft = MessageFormatter.format(format, arg);
470 log.error(ft.getMessage(), ft.getThrowable());
471 }
472 }
473
474 /**
475 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
476 * {@link Log} instance.
477 *
478 * <p>
479 * However, this form avoids superfluous object creation when the logger is disabled
480 * for level ERROR.
481 * </p>
482 *
483 * @param format
484 * the format string
485 * @param arg1
486 * the first argument
487 * @param arg2
488 * the second argument
489 */
490 public void error(String format, Object arg1, Object arg2) {
491 if (log.isErrorEnabled()) {
492 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
493 log.error(ft.getMessage(), ft.getThrowable());
494 }
495 }
496
497 /**
498 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
499 * {@link Log} instance.
500 *
501 * <p>
502 * However, this form avoids superfluous object creation when the logger is disabled
503 * for level ERROR.
504 * </p>
505 *
506 * @param format the format string
507 * @param arguments a list of 3 or more arguments
508 */
509 public void error(String format, Object... arguments) {
510 if (log.isErrorEnabled()) {
511 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
512 log.error(ft.getMessage(), ft.getThrowable());
513 }
514 }
515
516 /**
517 * Delegates to the {@link Log#error(java.lang.Object, java.lang.Throwable)} method of
518 * the underlying {@link Log} instance.
519 *
520 * @param msg
521 * the message accompanying the exception
522 * @param t
523 * the exception (throwable) to log
524 */
525
526 public void error(String msg, Throwable t) {
527 log.error(msg, t);
528 }
529
530 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j.impl;
26
27 import org.apache.commons.logging.Log;
28 import org.slf4j.Logger;
29 import org.slf4j.helpers.FormattingTuple;
30 import org.slf4j.helpers.MarkerIgnoringBase;
31 import org.slf4j.helpers.MessageFormatter;
32
33 /**
34 * A wrapper over {@link org.apache.commons.logging.Log
35 * org.apache.commons.logging.Log} in conformance with the {@link Logger}
36 * interface.
37 *
38 * @author Ceki G&uuml;lc&uuml;
39 */
40 public final class JCLLoggerAdapter extends MarkerIgnoringBase {
41
42 private static final long serialVersionUID = 4141593417490482209L;
43 final Log log;
44
45 // WARN: JCLLoggerAdapter constructor should have only package access so
46 // that only JCLLoggerFactory be able to create one.
47 JCLLoggerAdapter(Log log, String name) {
48 this.log = log;
49 this.name = name;
50 }
51
52 /**
53 * Delegates to the {@link Log#isTraceEnabled} method of the underlying
54 * {@link Log} instance.
55 */
56 public boolean isTraceEnabled() {
57 return log.isTraceEnabled();
58 }
59
60 //
61
62 /**
63 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
64 * {@link Log} instance.
65 *
66 * @param msg - the message object to be logged
67 */
68 public void trace(String msg) {
69 log.trace(msg);
70 }
71
72 /**
73 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
74 * {@link Log} instance.
75 *
76 * <p>
77 * However, this form avoids superfluous object creation when the logger is disabled
78 * for level TRACE.
79 * </p>
80 *
81 * @param format
82 * the format string
83 * @param arg
84 * the argument
85 */
86 public void trace(String format, Object arg) {
87 if (log.isTraceEnabled()) {
88 FormattingTuple ft = MessageFormatter.format(format, arg);
89 log.trace(ft.getMessage(), ft.getThrowable());
90 }
91 }
92
93 /**
94 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
95 * {@link Log} instance.
96 *
97 * <p>
98 * However, this form avoids superfluous object creation when the logger is disabled
99 * for level TRACE.
100 * </p>
101 *
102 * @param format
103 * the format string
104 * @param arg1
105 * the first argument
106 * @param arg2
107 * the second argument
108 */
109 public void trace(String format, Object arg1, Object arg2) {
110 if (log.isTraceEnabled()) {
111 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
112 log.trace(ft.getMessage(), ft.getThrowable());
113 }
114 }
115
116 /**
117 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
118 * {@link Log} instance.
119 *
120 * <p>
121 * However, this form avoids superfluous object creation when the logger is disabled
122 * for level TRACE.
123 * </p>
124 *
125 * @param format the format string
126 * @param arguments a list of 3 or more arguments
127 */
128 public void trace(String format, Object... arguments) {
129 if (log.isTraceEnabled()) {
130 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
131 log.trace(ft.getMessage(), ft.getThrowable());
132 }
133 }
134
135 /**
136 * Delegates to the {@link Log#trace(java.lang.Object, java.lang.Throwable)} method of
137 * the underlying {@link Log} instance.
138 *
139 * @param msg
140 * the message accompanying the exception
141 * @param t
142 * the exception (throwable) to log
143 */
144 public void trace(String msg, Throwable t) {
145 log.trace(msg, t);
146 }
147
148 /**
149 * Delegates to the {@link Log#isDebugEnabled} method of the underlying
150 * {@link Log} instance.
151 */
152 public boolean isDebugEnabled() {
153 return log.isDebugEnabled();
154 }
155
156 //
157
158 /**
159 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
160 * {@link Log} instance.
161 *
162 * @param msg - the message object to be logged
163 */
164 public void debug(String msg) {
165 log.debug(msg);
166 }
167
168 /**
169 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
170 * {@link Log} instance.
171 *
172 * <p>
173 * However, this form avoids superfluous object creation when the logger is disabled
174 * for level DEBUG.
175 * </p>
176 *
177 * @param format
178 * the format string
179 * @param arg
180 * the argument
181 */
182 public void debug(String format, Object arg) {
183 if (log.isDebugEnabled()) {
184 FormattingTuple ft = MessageFormatter.format(format, arg);
185 log.debug(ft.getMessage(), ft.getThrowable());
186 }
187 }
188
189 /**
190 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
191 * {@link Log} instance.
192 *
193 * <p>
194 * However, this form avoids superfluous object creation when the logger is disabled
195 * for level DEBUG.
196 * </p>
197 *
198 * @param format
199 * the format string
200 * @param arg1
201 * the first argument
202 * @param arg2
203 * the second argument
204 */
205 public void debug(String format, Object arg1, Object arg2) {
206 if (log.isDebugEnabled()) {
207 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
208 log.debug(ft.getMessage(), ft.getThrowable());
209 }
210 }
211
212 /**
213 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
214 * {@link Log} instance.
215 *
216 * <p>
217 * However, this form avoids superfluous object creation when the logger is disabled
218 * for level DEBUG.
219 * </p>
220 *
221 * @param format the format string
222 * @param arguments a list of 3 or more arguments
223 */
224 public void debug(String format, Object... arguments) {
225 if (log.isDebugEnabled()) {
226 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
227 log.debug(ft.getMessage(), ft.getThrowable());
228 }
229 }
230
231 /**
232 * Delegates to the {@link Log#debug(java.lang.Object, java.lang.Throwable)} method of
233 * the underlying {@link Log} instance.
234 *
235 * @param msg
236 * the message accompanying the exception
237 * @param t
238 * the exception (throwable) to log
239 */
240 public void debug(String msg, Throwable t) {
241 log.debug(msg, t);
242 }
243
244 /**
245 * Delegates to the {@link Log#isInfoEnabled} method of the underlying
246 * {@link Log} instance.
247 */
248 public boolean isInfoEnabled() {
249 return log.isInfoEnabled();
250 }
251
252 /**
253 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
254 * {@link Log} instance.
255 *
256 * @param msg - the message object to be logged
257 */
258 public void info(String msg) {
259 log.info(msg);
260 }
261
262 /**
263 * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying
264 * {@link Log} instance.
265 *
266 * <p>
267 * However, this form avoids superfluous object creation when the logger is disabled
268 * for level INFO.
269 * </p>
270 *
271 * @param format
272 * the format string
273 * @param arg
274 * the argument
275 */
276
277 public void info(String format, Object arg) {
278 if (log.isInfoEnabled()) {
279 FormattingTuple ft = MessageFormatter.format(format, arg);
280 log.info(ft.getMessage(), ft.getThrowable());
281 }
282 }
283
284 /**
285 * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying
286 * {@link Log} instance.
287 *
288 * <p>
289 * However, this form avoids superfluous object creation when the logger is disabled
290 * for level INFO.
291 * </p>
292 *
293 * @param format
294 * the format string
295 * @param arg1
296 * the first argument
297 * @param arg2
298 * the second argument
299 */
300 public void info(String format, Object arg1, Object arg2) {
301 if (log.isInfoEnabled()) {
302
303 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
304 log.info(ft.getMessage(), ft.getThrowable());
305 }
306 }
307
308 /**
309 * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying
310 * {@link Log} instance.
311 *
312 * <p>
313 * However, this form avoids superfluous object creation when the logger is disabled
314 * for level INFO.
315 * </p>
316 *
317 * @param format the format string
318 * @param arguments a list of 3 or more arguments
319 */
320 public void info(String format, Object... arguments) {
321 if (log.isInfoEnabled()) {
322 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
323 log.info(ft.getMessage(), ft.getThrowable());
324 }
325 }
326
327 /**
328 * Delegates to the {@link Log#info(java.lang.Object, java.lang.Throwable)} method of
329 * the underlying {@link Log} instance.
330 *
331 * @param msg
332 * the message accompanying the exception
333 * @param t
334 * the exception (throwable) to log
335 */
336 public void info(String msg, Throwable t) {
337 log.info(msg, t);
338 }
339
340 /**
341 * Delegates to the {@link Log#isWarnEnabled} method of the underlying
342 * {@link Log} instance.
343 */
344 public boolean isWarnEnabled() {
345 return log.isWarnEnabled();
346 }
347
348 /**
349 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
350 * {@link Log} instance.
351 *
352 * @param msg - the message object to be logged
353 */
354 public void warn(String msg) {
355 log.warn(msg);
356 }
357
358 /**
359 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
360 * {@link Log} instance.
361 *
362 * <p>
363 * However, this form avoids superfluous object creation when the logger is disabled
364 * for level WARN.
365 * </p>
366 *
367 * @param format
368 * the format string
369 * @param arg
370 * the argument
371 */
372 public void warn(String format, Object arg) {
373 if (log.isWarnEnabled()) {
374 FormattingTuple ft = MessageFormatter.format(format, arg);
375 log.warn(ft.getMessage(), ft.getThrowable());
376 }
377 }
378
379 /**
380 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
381 * {@link Log} instance.
382 *
383 * <p>
384 * However, this form avoids superfluous object creation when the logger is disabled
385 * for level WARN.
386 * </p>
387 *
388 * @param format
389 * the format string
390 * @param arg1
391 * the first argument
392 * @param arg2
393 * the second argument
394 */
395 public void warn(String format, Object arg1, Object arg2) {
396 if (log.isWarnEnabled()) {
397 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
398 log.warn(ft.getMessage(), ft.getThrowable());
399 }
400 }
401
402 /**
403 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
404 * {@link Log} instance.
405 *
406 * <p>
407 * However, this form avoids superfluous object creation when the logger is disabled
408 * for level WARN.
409 * </p>
410 *
411 * @param format the format string
412 * @param arguments a list of 3 or more arguments
413 */
414 public void warn(String format, Object... arguments) {
415 if (log.isWarnEnabled()) {
416 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
417 log.warn(ft.getMessage(), ft.getThrowable());
418 }
419 }
420
421 /**
422 * Delegates to the {@link Log#warn(java.lang.Object, java.lang.Throwable)} method of
423 * the underlying {@link Log} instance.
424 *
425 * @param msg
426 * the message accompanying the exception
427 * @param t
428 * the exception (throwable) to log
429 */
430
431 public void warn(String msg, Throwable t) {
432 log.warn(msg, t);
433 }
434
435 /**
436 * Delegates to the {@link Log#isErrorEnabled} method of the underlying
437 * {@link Log} instance.
438 */
439 public boolean isErrorEnabled() {
440 return log.isErrorEnabled();
441 }
442
443 /**
444 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
445 * {@link Log} instance.
446 *
447 * @param msg - the message object to be logged
448 */
449 public void error(String msg) {
450 log.error(msg);
451 }
452
453 /**
454 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
455 * {@link Log} instance.
456 *
457 * <p>
458 * However, this form avoids superfluous object creation when the logger is disabled
459 * for level ERROR.
460 * </p>
461 *
462 * @param format
463 * the format string
464 * @param arg
465 * the argument
466 */
467 public void error(String format, Object arg) {
468 if (log.isErrorEnabled()) {
469 FormattingTuple ft = MessageFormatter.format(format, arg);
470 log.error(ft.getMessage(), ft.getThrowable());
471 }
472 }
473
474 /**
475 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
476 * {@link Log} instance.
477 *
478 * <p>
479 * However, this form avoids superfluous object creation when the logger is disabled
480 * for level ERROR.
481 * </p>
482 *
483 * @param format
484 * the format string
485 * @param arg1
486 * the first argument
487 * @param arg2
488 * the second argument
489 */
490 public void error(String format, Object arg1, Object arg2) {
491 if (log.isErrorEnabled()) {
492 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
493 log.error(ft.getMessage(), ft.getThrowable());
494 }
495 }
496
497 /**
498 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
499 * {@link Log} instance.
500 *
501 * <p>
502 * However, this form avoids superfluous object creation when the logger is disabled
503 * for level ERROR.
504 * </p>
505 *
506 * @param format the format string
507 * @param arguments a list of 3 or more arguments
508 */
509 public void error(String format, Object... arguments) {
510 if (log.isErrorEnabled()) {
511 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
512 log.error(ft.getMessage(), ft.getThrowable());
513 }
514 }
515
516 /**
517 * Delegates to the {@link Log#error(java.lang.Object, java.lang.Throwable)} method of
518 * the underlying {@link Log} instance.
519 *
520 * @param msg
521 * the message accompanying the exception
522 * @param t
523 * the exception (throwable) to log
524 */
525
526 public void error(String msg, Throwable t) {
527 log.error(msg, t);
528 }
529
530 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.apache.commons.logging.LogFactory;
30 import org.slf4j.ILoggerFactory;
31 import org.slf4j.Logger;
32 import org.slf4j.helpers.Util;
33
34 /**
35 * JCLLoggerFactory is an implementation of {@link ILoggerFactory} returning the
36 * appropriately named {@link JCLLoggerAdapter} instance.
37 *
38 * @author Ceki G&uuml;lc&uuml;
39 */
40 public class JCLLoggerFactory implements ILoggerFactory {
41
42 private static final String JCL_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#jclDelegationLoop";
43
44 // check for delegation loops
45 static {
46 try {
47 Class.forName("org.apache.commons.logging.impl.SLF4JLogFactory");
48 String part1 = "Detected both jcl-over-slf4j.jar AND bound slf4j-jcl.jar on the class path, preempting StackOverflowError. ";
49 String part2 = "See also " + JCL_DELEGATION_LOOP_URL + " for more details.";
50
51 Util.report(part1);
52 Util.report(part2);
53 throw new IllegalStateException(part1 + part2);
54 } catch (ClassNotFoundException e) {
55 // this is the good case
56 }
57 }
58
59 // key: name (String), value: a JCLLoggerAdapter;
60 final ConcurrentMap<String, Logger> loggerMap;
61
62 public JCLLoggerFactory() {
63 loggerMap = new ConcurrentHashMap<String, Logger>();
64 }
65
66 /*
67 * (non-Javadoc)
68 *
69 * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String)
70 */
71 public Logger getLogger(String name) {
72 Logger slf4jLogger = loggerMap.get(name);
73 if (slf4jLogger != null) {
74 return slf4jLogger;
75 } else {
76 org.apache.commons.logging.Log jclLogger = LogFactory.getLog(name);
77 Logger newInstance = new JCLLoggerAdapter(jclLogger, name);
78 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
79 return oldInstance == null ? newInstance : oldInstance;
80 }
81 }
82 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.apache.commons.logging.LogFactory;
30 import org.slf4j.ILoggerFactory;
31 import org.slf4j.Logger;
32 import org.slf4j.helpers.Util;
33
34 /**
35 * JCLLoggerFactory is an implementation of {@link ILoggerFactory} returning the
36 * appropriately named {@link JCLLoggerAdapter} instance.
37 *
38 * @author Ceki G&uuml;lc&uuml;
39 */
40 public class JCLLoggerFactory implements ILoggerFactory {
41
42 private static final String JCL_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#jclDelegationLoop";
43
44 // check for delegation loops
45 static {
46 try {
47 Class.forName("org.apache.commons.logging.impl.SLF4JLogFactory");
48 String part1 = "Detected both jcl-over-slf4j.jar AND bound slf4j-jcl.jar on the class path, preempting StackOverflowError. ";
49 String part2 = "See also " + JCL_DELEGATION_LOOP_URL + " for more details.";
50
51 Util.report(part1);
52 Util.report(part2);
53 throw new IllegalStateException(part1 + part2);
54 } catch (ClassNotFoundException e) {
55 // this is the good case
56 }
57 }
58
59 // key: name (String), value: a JCLLoggerAdapter;
60 final ConcurrentMap<String, Logger> loggerMap;
61
62 public JCLLoggerFactory() {
63 loggerMap = new ConcurrentHashMap<String, Logger>();
64 }
65
66 /*
67 * (non-Javadoc)
68 *
69 * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String)
70 */
71 public Logger getLogger(String name) {
72 Logger slf4jLogger = loggerMap.get(name);
73 if (slf4jLogger != null) {
74 return slf4jLogger;
75 } else {
76 org.apache.commons.logging.Log jclLogger = LogFactory.getLog(name);
77 Logger newInstance = new JCLLoggerAdapter(jclLogger, name);
78 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
79 return oldInstance == null ? newInstance : oldInstance;
80 }
81 }
82 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class StaticLoggerBinder implements LoggerFactoryBinder {
37
38 /**
39 * The unique instance of this class.
40 */
41 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
42
43 /**
44 * Return the singleton of this class.
45 *
46 * @return the StaticLoggerBinder singleton
47 */
48 public static final StaticLoggerBinder getSingleton() {
49 return SINGLETON;
50 }
51
52 /**
53 * Declare the version of the SLF4J API this implementation is compiled against.
54 * The value of this field is modified with each major release.
55 */
56 // to avoid constant folding by the compiler, this field must *not* be final
57 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
58
59 // Binding specific code:
60 private static final String loggerFactoryClassStr = JCLLoggerFactory.class.getName();
61
62 /**
63 * The ILoggerFactory instance returned by the {@link #getLoggerFactory}
64 * method should always be the same object
65 */
66 private final ILoggerFactory loggerFactory;
67
68 private StaticLoggerBinder() {
69 // Binding specific code:
70 loggerFactory = new JCLLoggerFactory();
71 }
72
73 public ILoggerFactory getLoggerFactory() {
74 return loggerFactory;
75 }
76
77 public String getLoggerFactoryClassStr() {
78 return loggerFactoryClassStr;
79 }
80 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class StaticLoggerBinder implements LoggerFactoryBinder {
37
38 /**
39 * The unique instance of this class.
40 */
41 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
42
43 /**
44 * Return the singleton of this class.
45 *
46 * @return the StaticLoggerBinder singleton
47 */
48 public static final StaticLoggerBinder getSingleton() {
49 return SINGLETON;
50 }
51
52 /**
53 * Declare the version of the SLF4J API this implementation is compiled against.
54 * The value of this field is modified with each major release.
55 */
56 // to avoid constant folding by the compiler, this field must *not* be final
57 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
58
59 // Binding specific code:
60 private static final String loggerFactoryClassStr = JCLLoggerFactory.class.getName();
61
62 /**
63 * The ILoggerFactory instance returned by the {@link #getLoggerFactory}
64 * method should always be the same object
65 */
66 private final ILoggerFactory loggerFactory;
67
68 private StaticLoggerBinder() {
69 // Binding specific code:
70 loggerFactory = new JCLLoggerFactory();
71 }
72
73 public ILoggerFactory getLoggerFactory() {
74 return loggerFactory;
75 }
76
77 public String getLoggerFactoryClassStr() {
78 return loggerFactoryClassStr;
79 }
80 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link NOPMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticMDCBinder singleton
48 * @since 1.7.14
49 */
50 public static final StaticMDCBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Currently this method always returns an instance of
56 * {@link NOPMDCAdapter}.
57 *
58 * @return instance of NOPMDCAdapter
59 * @since 1.7.14
60 */
61 public MDCAdapter getMDCA() {
62 return new NOPMDCAdapter();
63 }
64
65 public String getMDCAdapterClassStr() {
66 return NOPMDCAdapter.class.getName();
67 }
68 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link NOPMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticMDCBinder singleton
48 * @since 1.7.14
49 */
50 public static final StaticMDCBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Currently this method always returns an instance of
56 * {@link NOPMDCAdapter}.
57 *
58 * @return instance of NOPMDCAdapter
59 * @since 1.7.14
60 */
61 public MDCAdapter getMDCA() {
62 return new NOPMDCAdapter();
63 }
64
65 public String getMDCAdapterClassStr() {
66 return NOPMDCAdapter.class.getName();
67 }
68 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Return the singleton of this class.
52 *
53 * @return the StaticMarkerBinder singleton
54 * @since 1.7.14
55 */
56 public static StaticMarkerBinder getSingleton() {
57 return SINGLETON;
58 }
59
60 /**
61 * Currently this method always returns an instance of
62 * {@link BasicMarkerFactory}.
63 */
64 public IMarkerFactory getMarkerFactory() {
65 return markerFactory;
66 }
67
68 /**
69 * Currently, this method returns the class name of
70 * {@link BasicMarkerFactory}.
71 */
72 public String getMarkerFactoryClassStr() {
73 return BasicMarkerFactory.class.getName();
74 }
75
76 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Return the singleton of this class.
52 *
53 * @return the StaticMarkerBinder singleton
54 * @since 1.7.14
55 */
56 public static StaticMarkerBinder getSingleton() {
57 return SINGLETON;
58 }
59
60 /**
61 * Currently this method always returns an instance of
62 * {@link BasicMarkerFactory}.
63 */
64 public IMarkerFactory getMarkerFactory() {
65 return markerFactory;
66 }
67
68 /**
69 * Currently, this method returns the class name of
70 * {@link BasicMarkerFactory}.
71 */
72 public String getMarkerFactoryClassStr() {
73 return BasicMarkerFactory.class.getName();
74 }
75
76 }
0 Implementation-Title: slf4j-jcl
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.jcl
3 Bundle-Name: slf4j-jcl
4 Bundle-Vendor: SLF4J.ORG
5 Require-Bundle: slf4j.api
6 Bundle-RequiredExecutionEnvironment: J2SE-1.5
7 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
8 Import-Package: org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, org.apache.commons.logging
0 Implementation-Title: slf4j-jcl
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.jcl
3 Bundle-Name: slf4j-jcl
4 Bundle-Vendor: SLF4J.ORG
5 Require-Bundle: slf4j.api
6 Bundle-RequiredExecutionEnvironment: J2SE-1.5
7 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
8 Import-Package: org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, org.apache.commons.logging
99 Fragment-Host: slf4j.api
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertNull;
27
28 import java.util.logging.Level;
29
30 import org.junit.After;
31 import org.junit.Before;
32 import org.junit.Test;
33
34 /**
35 * Test whether invoking the SLF4J API causes problems or not.
36 *
37 * @author Ceki Gulcu
38 *
39 */
40 public class InvocationTest {
41
42 Level oldLevel;
43 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
44
45 @Before
46 public void setUp() throws Exception {
47 oldLevel = root.getLevel();
48 root.setLevel(Level.OFF);
49 }
50
51 @After
52 public void tearDown() throws Exception {
53 root.setLevel(oldLevel);
54 }
55
56 @Test
57 public void test1() {
58 Logger logger = LoggerFactory.getLogger("test1");
59 logger.debug("Hello world.");
60 }
61
62 @Test
63 public void test2() {
64 Integer i1 = new Integer(1);
65 Integer i2 = new Integer(2);
66 Integer i3 = new Integer(3);
67 Exception e = new Exception("This is a test exception.");
68 Logger logger = LoggerFactory.getLogger("test2");
69
70 logger.debug("Hello world 1.");
71 logger.debug("Hello world {}", i1);
72 logger.debug("val={} val={}", i1, i2);
73 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
74
75 logger.debug("Hello world 2", e);
76 logger.info("Hello world 2.");
77
78 logger.warn("Hello world 3.");
79 logger.warn("Hello world 3", e);
80
81 logger.error("Hello world 4.");
82 logger.error("Hello world {}", new Integer(3));
83 logger.error("Hello world 4.", e);
84 }
85
86 @Test
87 public void testNull() {
88 Logger logger = LoggerFactory.getLogger("testNull");
89 logger.debug(null);
90 logger.info(null);
91 logger.warn(null);
92 logger.error(null);
93
94 Exception e = new Exception("This is a test exception.");
95 logger.debug(null, e);
96 logger.info(null, e);
97 logger.warn(null, e);
98 logger.error(null, e);
99 }
100
101 @Test
102 public void testMarker() {
103 Logger logger = LoggerFactory.getLogger("testMarker");
104 Marker blue = MarkerFactory.getMarker("BLUE");
105 logger.debug(blue, "hello");
106 logger.info(blue, "hello");
107 logger.warn(blue, "hello");
108 logger.error(blue, "hello");
109
110 logger.debug(blue, "hello {}", "world");
111 logger.info(blue, "hello {}", "world");
112 logger.warn(blue, "hello {}", "world");
113 logger.error(blue, "hello {}", "world");
114
115 logger.debug(blue, "hello {} and {} ", "world", "universe");
116 logger.info(blue, "hello {} and {} ", "world", "universe");
117 logger.warn(blue, "hello {} and {} ", "world", "universe");
118 logger.error(blue, "hello {} and {} ", "world", "universe");
119 }
120
121 @Test
122 public void testMDC() {
123 MDC.put("k", "v");
124 assertNull(MDC.get("k"));
125 MDC.remove("k");
126 assertNull(MDC.get("k"));
127 MDC.clear();
128 }
129 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertNull;
27
28 import java.util.logging.Level;
29
30 import org.junit.After;
31 import org.junit.Before;
32 import org.junit.Test;
33
34 /**
35 * Test whether invoking the SLF4J API causes problems or not.
36 *
37 * @author Ceki Gulcu
38 *
39 */
40 public class InvocationTest {
41
42 Level oldLevel;
43 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
44
45 @Before
46 public void setUp() throws Exception {
47 oldLevel = root.getLevel();
48 root.setLevel(Level.OFF);
49 }
50
51 @After
52 public void tearDown() throws Exception {
53 root.setLevel(oldLevel);
54 }
55
56 @Test
57 public void test1() {
58 Logger logger = LoggerFactory.getLogger("test1");
59 logger.debug("Hello world.");
60 }
61
62 @Test
63 public void test2() {
64 Integer i1 = new Integer(1);
65 Integer i2 = new Integer(2);
66 Integer i3 = new Integer(3);
67 Exception e = new Exception("This is a test exception.");
68 Logger logger = LoggerFactory.getLogger("test2");
69
70 logger.debug("Hello world 1.");
71 logger.debug("Hello world {}", i1);
72 logger.debug("val={} val={}", i1, i2);
73 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
74
75 logger.debug("Hello world 2", e);
76 logger.info("Hello world 2.");
77
78 logger.warn("Hello world 3.");
79 logger.warn("Hello world 3", e);
80
81 logger.error("Hello world 4.");
82 logger.error("Hello world {}", new Integer(3));
83 logger.error("Hello world 4.", e);
84 }
85
86 @Test
87 public void testNull() {
88 Logger logger = LoggerFactory.getLogger("testNull");
89 logger.debug(null);
90 logger.info(null);
91 logger.warn(null);
92 logger.error(null);
93
94 Exception e = new Exception("This is a test exception.");
95 logger.debug(null, e);
96 logger.info(null, e);
97 logger.warn(null, e);
98 logger.error(null, e);
99 }
100
101 @Test
102 public void testMarker() {
103 Logger logger = LoggerFactory.getLogger("testMarker");
104 Marker blue = MarkerFactory.getMarker("BLUE");
105 logger.debug(blue, "hello");
106 logger.info(blue, "hello");
107 logger.warn(blue, "hello");
108 logger.error(blue, "hello");
109
110 logger.debug(blue, "hello {}", "world");
111 logger.info(blue, "hello {}", "world");
112 logger.warn(blue, "hello {}", "world");
113 logger.error(blue, "hello {}", "world");
114
115 logger.debug(blue, "hello {} and {} ", "world", "universe");
116 logger.info(blue, "hello {} and {} ", "world", "universe");
117 logger.warn(blue, "hello {} and {} ", "world", "universe");
118 logger.error(blue, "hello {} and {} ", "world", "universe");
119 }
120
121 @Test
122 public void testMDC() {
123 MDC.put("k", "v");
124 assertNull(MDC.get("k"));
125 MDC.remove("k");
126 assertNull(MDC.get("k"));
127 MDC.clear();
128 }
129 }
0 Copyright (c) 2004-2007 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>slf4j-jdk14</artifactId>
13 <packaging>jar</packaging>
14 <name>SLF4J JDK14 Binding</name>
15 <description>SLF4J JDK14 Binding</description>
16 <url>http://www.slf4j.org</url>
17
18 <dependencies>
19 <dependency>
20 <groupId>org.slf4j</groupId>
21 <artifactId>slf4j-api</artifactId>
22 </dependency>
23
24 <dependency>
25 <groupId>org.slf4j</groupId>
26 <artifactId>slf4j-api</artifactId>
27 <type>test-jar</type>
28 <version>${project.version}</version>
29 <scope>test</scope>
30 </dependency>
31 </dependencies>
32
33 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>slf4j-jdk14</artifactId>
13 <packaging>jar</packaging>
14 <name>SLF4J JDK14 Binding</name>
15 <description>SLF4J JDK14 Binding</description>
16 <url>http://www.slf4j.org</url>
17
18 <dependencies>
19 <dependency>
20 <groupId>org.slf4j</groupId>
21 <artifactId>slf4j-api</artifactId>
22 </dependency>
23
24 <dependency>
25 <groupId>org.slf4j</groupId>
26 <artifactId>slf4j-api</artifactId>
27 <type>test-jar</type>
28 <version>${project.version}</version>
29 <scope>test</scope>
30 </dependency>
31 </dependencies>
32
33
34 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.logging.Level;
27 import java.util.logging.LogRecord;
28
29 import org.slf4j.Logger;
30 import org.slf4j.Marker;
31 import org.slf4j.event.EventConstants;
32 import org.slf4j.event.LoggingEvent;
33 import org.slf4j.helpers.FormattingTuple;
34 import org.slf4j.helpers.MarkerIgnoringBase;
35 import org.slf4j.helpers.MessageFormatter;
36 import org.slf4j.spi.LocationAwareLogger;
37
38 /**
39 * A wrapper over {@link java.util.logging.Logger java.util.logging.Logger} in
40 * conformity with the {@link Logger} interface. Note that the logging levels
41 * mentioned in this class refer to those defined in the java.util.logging
42 * package.
43 *
44 * @author Ceki G&uuml;lc&uuml;
45 * @author Peter Royal
46 */
47 public final class JDK14LoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger {
48
49 private static final long serialVersionUID = -8053026990503422791L;
50
51 transient final java.util.logging.Logger logger;
52
53 // WARN: JDK14LoggerAdapter constructor should have only package access so
54 // that only JDK14LoggerFactory be able to create one.
55 JDK14LoggerAdapter(java.util.logging.Logger logger) {
56 this.logger = logger;
57 this.name = logger.getName();
58 }
59
60 /**
61 * Is this logger instance enabled for the FINEST level?
62 *
63 * @return True if this Logger is enabled for level FINEST, false otherwise.
64 */
65 public boolean isTraceEnabled() {
66 return logger.isLoggable(Level.FINEST);
67 }
68
69 /**
70 * Log a message object at level FINEST.
71 *
72 * @param msg
73 * - the message object to be logged
74 */
75 public void trace(String msg) {
76 if (logger.isLoggable(Level.FINEST)) {
77 log(SELF, Level.FINEST, msg, null);
78 }
79 }
80
81 /**
82 * Log a message at level FINEST according to the specified format and
83 * argument.
84 *
85 * <p>
86 * This form avoids superfluous object creation when the logger is disabled
87 * for level FINEST.
88 * </p>
89 *
90 * @param format
91 * the format string
92 * @param arg
93 * the argument
94 */
95 public void trace(String format, Object arg) {
96 if (logger.isLoggable(Level.FINEST)) {
97 FormattingTuple ft = MessageFormatter.format(format, arg);
98 log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable());
99 }
100 }
101
102 /**
103 * Log a message at level FINEST according to the specified format and
104 * arguments.
105 *
106 * <p>
107 * This form avoids superfluous object creation when the logger is disabled
108 * for the FINEST level.
109 * </p>
110 *
111 * @param format
112 * the format string
113 * @param arg1
114 * the first argument
115 * @param arg2
116 * the second argument
117 */
118 public void trace(String format, Object arg1, Object arg2) {
119 if (logger.isLoggable(Level.FINEST)) {
120 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
121 log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable());
122 }
123 }
124
125 /**
126 * Log a message at level FINEST according to the specified format and
127 * arguments.
128 *
129 * <p>
130 * This form avoids superfluous object creation when the logger is disabled
131 * for the FINEST level.
132 * </p>
133 *
134 * @param format
135 * the format string
136 * @param argArray
137 * an array of arguments
138 */
139 public void trace(String format, Object... argArray) {
140 if (logger.isLoggable(Level.FINEST)) {
141 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
142 log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable());
143 }
144 }
145
146 /**
147 * Log an exception (throwable) at level FINEST with an accompanying message.
148 *
149 * @param msg
150 * the message accompanying the exception
151 * @param t
152 * the exception (throwable) to log
153 */
154 public void trace(String msg, Throwable t) {
155 if (logger.isLoggable(Level.FINEST)) {
156 log(SELF, Level.FINEST, msg, t);
157 }
158 }
159
160 /**
161 * Is this logger instance enabled for the FINE level?
162 *
163 * @return True if this Logger is enabled for level FINE, false otherwise.
164 */
165 public boolean isDebugEnabled() {
166 return logger.isLoggable(Level.FINE);
167 }
168
169 /**
170 * Log a message object at level FINE.
171 *
172 * @param msg
173 * - the message object to be logged
174 */
175 public void debug(String msg) {
176 if (logger.isLoggable(Level.FINE)) {
177 log(SELF, Level.FINE, msg, null);
178 }
179 }
180
181 /**
182 * Log a message at level FINE according to the specified format and argument.
183 *
184 * <p>
185 * This form avoids superfluous object creation when the logger is disabled
186 * for level FINE.
187 * </p>
188 *
189 * @param format
190 * the format string
191 * @param arg
192 * the argument
193 */
194 public void debug(String format, Object arg) {
195 if (logger.isLoggable(Level.FINE)) {
196 FormattingTuple ft = MessageFormatter.format(format, arg);
197 log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable());
198 }
199 }
200
201 /**
202 * Log a message at level FINE according to the specified format and
203 * arguments.
204 *
205 * <p>
206 * This form avoids superfluous object creation when the logger is disabled
207 * for the FINE level.
208 * </p>
209 *
210 * @param format
211 * the format string
212 * @param arg1
213 * the first argument
214 * @param arg2
215 * the second argument
216 */
217 public void debug(String format, Object arg1, Object arg2) {
218 if (logger.isLoggable(Level.FINE)) {
219 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
220 log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable());
221 }
222 }
223
224 /**
225 * Log a message at level FINE according to the specified format and
226 * arguments.
227 *
228 * <p>
229 * This form avoids superfluous object creation when the logger is disabled
230 * for the FINE level.
231 * </p>
232 *
233 * @param format
234 * the format string
235 * @param argArray
236 * an array of arguments
237 */
238 public void debug(String format, Object... argArray) {
239 if (logger.isLoggable(Level.FINE)) {
240 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
241 log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable());
242 }
243 }
244
245 /**
246 * Log an exception (throwable) at level FINE with an accompanying message.
247 *
248 * @param msg
249 * the message accompanying the exception
250 * @param t
251 * the exception (throwable) to log
252 */
253 public void debug(String msg, Throwable t) {
254 if (logger.isLoggable(Level.FINE)) {
255 log(SELF, Level.FINE, msg, t);
256 }
257 }
258
259 /**
260 * Is this logger instance enabled for the INFO level?
261 *
262 * @return True if this Logger is enabled for the INFO level, false otherwise.
263 */
264 public boolean isInfoEnabled() {
265 return logger.isLoggable(Level.INFO);
266 }
267
268 /**
269 * Log a message object at the INFO level.
270 *
271 * @param msg
272 * - the message object to be logged
273 */
274 public void info(String msg) {
275 if (logger.isLoggable(Level.INFO)) {
276 log(SELF, Level.INFO, msg, null);
277 }
278 }
279
280 /**
281 * Log a message at level INFO according to the specified format and argument.
282 *
283 * <p>
284 * This form avoids superfluous object creation when the logger is disabled
285 * for the INFO level.
286 * </p>
287 *
288 * @param format
289 * the format string
290 * @param arg
291 * the argument
292 */
293 public void info(String format, Object arg) {
294 if (logger.isLoggable(Level.INFO)) {
295 FormattingTuple ft = MessageFormatter.format(format, arg);
296 log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable());
297 }
298 }
299
300 /**
301 * Log a message at the INFO level according to the specified format and
302 * arguments.
303 *
304 * <p>
305 * This form avoids superfluous object creation when the logger is disabled
306 * for the INFO level.
307 * </p>
308 *
309 * @param format
310 * the format string
311 * @param arg1
312 * the first argument
313 * @param arg2
314 * the second argument
315 */
316 public void info(String format, Object arg1, Object arg2) {
317 if (logger.isLoggable(Level.INFO)) {
318 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
319 log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable());
320 }
321 }
322
323 /**
324 * Log a message at level INFO according to the specified format and
325 * arguments.
326 *
327 * <p>
328 * This form avoids superfluous object creation when the logger is disabled
329 * for the INFO level.
330 * </p>
331 *
332 * @param format
333 * the format string
334 * @param argArray
335 * an array of arguments
336 */
337 public void info(String format, Object... argArray) {
338 if (logger.isLoggable(Level.INFO)) {
339 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
340 log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable());
341 }
342 }
343
344 /**
345 * Log an exception (throwable) at the INFO level with an accompanying
346 * message.
347 *
348 * @param msg
349 * the message accompanying the exception
350 * @param t
351 * the exception (throwable) to log
352 */
353 public void info(String msg, Throwable t) {
354 if (logger.isLoggable(Level.INFO)) {
355 log(SELF, Level.INFO, msg, t);
356 }
357 }
358
359 /**
360 * Is this logger instance enabled for the WARNING level?
361 *
362 * @return True if this Logger is enabled for the WARNING level, false
363 * otherwise.
364 */
365 public boolean isWarnEnabled() {
366 return logger.isLoggable(Level.WARNING);
367 }
368
369 /**
370 * Log a message object at the WARNING level.
371 *
372 * @param msg
373 * - the message object to be logged
374 */
375 public void warn(String msg) {
376 if (logger.isLoggable(Level.WARNING)) {
377 log(SELF, Level.WARNING, msg, null);
378 }
379 }
380
381 /**
382 * Log a message at the WARNING level according to the specified format and
383 * argument.
384 *
385 * <p>
386 * This form avoids superfluous object creation when the logger is disabled
387 * for the WARNING level.
388 * </p>
389 *
390 * @param format
391 * the format string
392 * @param arg
393 * the argument
394 */
395 public void warn(String format, Object arg) {
396 if (logger.isLoggable(Level.WARNING)) {
397 FormattingTuple ft = MessageFormatter.format(format, arg);
398 log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable());
399 }
400 }
401
402 /**
403 * Log a message at the WARNING level according to the specified format and
404 * arguments.
405 *
406 * <p>
407 * This form avoids superfluous object creation when the logger is disabled
408 * for the WARNING level.
409 * </p>
410 *
411 * @param format
412 * the format string
413 * @param arg1
414 * the first argument
415 * @param arg2
416 * the second argument
417 */
418 public void warn(String format, Object arg1, Object arg2) {
419 if (logger.isLoggable(Level.WARNING)) {
420 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
421 log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable());
422 }
423 }
424
425 /**
426 * Log a message at level WARNING according to the specified format and
427 * arguments.
428 *
429 * <p>
430 * This form avoids superfluous object creation when the logger is disabled
431 * for the WARNING level.
432 * </p>
433 *
434 * @param format
435 * the format string
436 * @param argArray
437 * an array of arguments
438 */
439 public void warn(String format, Object... argArray) {
440 if (logger.isLoggable(Level.WARNING)) {
441 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
442 log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable());
443 }
444 }
445
446 /**
447 * Log an exception (throwable) at the WARNING level with an accompanying
448 * message.
449 *
450 * @param msg
451 * the message accompanying the exception
452 * @param t
453 * the exception (throwable) to log
454 */
455 public void warn(String msg, Throwable t) {
456 if (logger.isLoggable(Level.WARNING)) {
457 log(SELF, Level.WARNING, msg, t);
458 }
459 }
460
461 /**
462 * Is this logger instance enabled for level SEVERE?
463 *
464 * @return True if this Logger is enabled for level SEVERE, false otherwise.
465 */
466 public boolean isErrorEnabled() {
467 return logger.isLoggable(Level.SEVERE);
468 }
469
470 /**
471 * Log a message object at the SEVERE level.
472 *
473 * @param msg
474 * - the message object to be logged
475 */
476 public void error(String msg) {
477 if (logger.isLoggable(Level.SEVERE)) {
478 log(SELF, Level.SEVERE, msg, null);
479 }
480 }
481
482 /**
483 * Log a message at the SEVERE level according to the specified format and
484 * argument.
485 *
486 * <p>
487 * This form avoids superfluous object creation when the logger is disabled
488 * for the SEVERE level.
489 * </p>
490 *
491 * @param format
492 * the format string
493 * @param arg
494 * the argument
495 */
496 public void error(String format, Object arg) {
497 if (logger.isLoggable(Level.SEVERE)) {
498 FormattingTuple ft = MessageFormatter.format(format, arg);
499 log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable());
500 }
501 }
502
503 /**
504 * Log a message at the SEVERE level according to the specified format and
505 * arguments.
506 *
507 * <p>
508 * This form avoids superfluous object creation when the logger is disabled
509 * for the SEVERE level.
510 * </p>
511 *
512 * @param format
513 * the format string
514 * @param arg1
515 * the first argument
516 * @param arg2
517 * the second argument
518 */
519 public void error(String format, Object arg1, Object arg2) {
520 if (logger.isLoggable(Level.SEVERE)) {
521 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
522 log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable());
523 }
524 }
525
526 /**
527 * Log a message at level SEVERE according to the specified format and
528 * arguments.
529 *
530 * <p>
531 * This form avoids superfluous object creation when the logger is disabled
532 * for the SEVERE level.
533 * </p>
534 *
535 * @param format
536 * the format string
537 * @param arguments
538 * an array of arguments
539 */
540 public void error(String format, Object... arguments) {
541 if (logger.isLoggable(Level.SEVERE)) {
542 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
543 log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable());
544 }
545 }
546
547 /**
548 * Log an exception (throwable) at the SEVERE level with an accompanying
549 * message.
550 *
551 * @param msg
552 * the message accompanying the exception
553 * @param t
554 * the exception (throwable) to log
555 */
556 public void error(String msg, Throwable t) {
557 if (logger.isLoggable(Level.SEVERE)) {
558 log(SELF, Level.SEVERE, msg, t);
559 }
560 }
561
562 /**
563 * Log the message at the specified level with the specified throwable if any.
564 * This method creates a LogRecord and fills in caller date before calling
565 * this instance's JDK14 logger.
566 *
567 * See bug report #13 for more details.
568 *
569 * @param level
570 * @param msg
571 * @param t
572 */
573 private void log(String callerFQCN, Level level, String msg, Throwable t) {
574 // millis and thread are filled by the constructor
575 LogRecord record = new LogRecord(level, msg);
576 record.setLoggerName(getName());
577 record.setThrown(t);
578 // Note: parameters in record are not set because SLF4J only
579 // supports a single formatting style
580 fillCallerData(callerFQCN, record);
581 logger.log(record);
582 }
583
584 static String SELF = JDK14LoggerAdapter.class.getName();
585 static String SUPER = MarkerIgnoringBase.class.getName();
586
587 /**
588 * Fill in caller data if possible.
589 *
590 * @param record
591 * The record to update
592 */
593 final private void fillCallerData(String callerFQCN, LogRecord record) {
594 StackTraceElement[] steArray = new Throwable().getStackTrace();
595
596 int selfIndex = -1;
597 for (int i = 0; i < steArray.length; i++) {
598 final String className = steArray[i].getClassName();
599 if (className.equals(callerFQCN) || className.equals(SUPER)) {
600 selfIndex = i;
601 break;
602 }
603 }
604
605 int found = -1;
606 for (int i = selfIndex + 1; i < steArray.length; i++) {
607 final String className = steArray[i].getClassName();
608 if (!(className.equals(callerFQCN) || className.equals(SUPER))) {
609 found = i;
610 break;
611 }
612 }
613
614 if (found != -1) {
615 StackTraceElement ste = steArray[found];
616 // setting the class name has the side effect of setting
617 // the needToInferCaller variable to false.
618 record.setSourceClassName(ste.getClassName());
619 record.setSourceMethodName(ste.getMethodName());
620 }
621 }
622
623 public void log(Marker marker, String callerFQCN, int level, String message, Object[] argArray, Throwable t) {
624 Level julLevel = slf4jLevelIntToJULLevel(level);
625 // the logger.isLoggable check avoids the unconditional
626 // construction of location data for disabled log
627 // statements. As of 2008-07-31, callers of this method
628 // do not perform this check. See also
629 // http://jira.qos.ch/browse/SLF4J-81
630 if (logger.isLoggable(julLevel)) {
631 log(callerFQCN, julLevel, message, t);
632 }
633 }
634
635 private Level slf4jLevelIntToJULLevel(int slf4jLevelInt) {
636 Level julLevel;
637 switch (slf4jLevelInt) {
638 case LocationAwareLogger.TRACE_INT:
639 julLevel = Level.FINEST;
640 break;
641 case LocationAwareLogger.DEBUG_INT:
642 julLevel = Level.FINE;
643 break;
644 case LocationAwareLogger.INFO_INT:
645 julLevel = Level.INFO;
646 break;
647 case LocationAwareLogger.WARN_INT:
648 julLevel = Level.WARNING;
649 break;
650 case LocationAwareLogger.ERROR_INT:
651 julLevel = Level.SEVERE;
652 break;
653 default:
654 throw new IllegalStateException("Level number " + slf4jLevelInt + " is not recognized.");
655 }
656 return julLevel;
657 }
658
659 /**
660 * @since 1.7.15
661 */
662 public void log(LoggingEvent event) {
663 Level julLevel = slf4jLevelIntToJULLevel(event.getLevel().toInt());
664 if (logger.isLoggable(julLevel)) {
665 LogRecord record = eventToRecord(event, julLevel);
666 logger.log(record);
667 }
668 }
669
670 private LogRecord eventToRecord(LoggingEvent event, Level julLevel) {
671 String format = event.getMessage();
672 Object[] arguments = event.getArgumentArray();
673 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
674 if (ft.getThrowable() != null && event.getThrowable() != null) {
675 throw new IllegalArgumentException("both last element in argument array and last argument are of type Throwable");
676 }
677
678 Throwable t = event.getThrowable();
679 if (ft.getThrowable() != null) {
680 t = ft.getThrowable();
681 throw new IllegalStateException("fix above code");
682 }
683
684 LogRecord record = new LogRecord(julLevel, ft.getMessage());
685 record.setLoggerName(event.getLoggerName());
686 record.setMillis(event.getTimeStamp());
687 record.setSourceClassName(EventConstants.NA_SUBST);
688 record.setSourceMethodName(EventConstants.NA_SUBST);
689
690 record.setThrown(t);
691 return record;
692 }
693 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.logging.Level;
27 import java.util.logging.LogRecord;
28
29 import org.slf4j.Logger;
30 import org.slf4j.Marker;
31 import org.slf4j.event.EventConstants;
32 import org.slf4j.event.LoggingEvent;
33 import org.slf4j.helpers.FormattingTuple;
34 import org.slf4j.helpers.MarkerIgnoringBase;
35 import org.slf4j.helpers.MessageFormatter;
36 import org.slf4j.spi.LocationAwareLogger;
37
38 /**
39 * A wrapper over {@link java.util.logging.Logger java.util.logging.Logger} in
40 * conformity with the {@link Logger} interface. Note that the logging levels
41 * mentioned in this class refer to those defined in the java.util.logging
42 * package.
43 *
44 * @author Ceki G&uuml;lc&uuml;
45 * @author Peter Royal
46 */
47 public final class JDK14LoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger {
48
49 private static final long serialVersionUID = -8053026990503422791L;
50
51 transient final java.util.logging.Logger logger;
52
53 // WARN: JDK14LoggerAdapter constructor should have only package access so
54 // that only JDK14LoggerFactory be able to create one.
55 JDK14LoggerAdapter(java.util.logging.Logger logger) {
56 this.logger = logger;
57 this.name = logger.getName();
58 }
59
60 /**
61 * Is this logger instance enabled for the FINEST level?
62 *
63 * @return True if this Logger is enabled for level FINEST, false otherwise.
64 */
65 public boolean isTraceEnabled() {
66 return logger.isLoggable(Level.FINEST);
67 }
68
69 /**
70 * Log a message object at level FINEST.
71 *
72 * @param msg
73 * - the message object to be logged
74 */
75 public void trace(String msg) {
76 if (logger.isLoggable(Level.FINEST)) {
77 log(SELF, Level.FINEST, msg, null);
78 }
79 }
80
81 /**
82 * Log a message at level FINEST according to the specified format and
83 * argument.
84 *
85 * <p>
86 * This form avoids superfluous object creation when the logger is disabled
87 * for level FINEST.
88 * </p>
89 *
90 * @param format
91 * the format string
92 * @param arg
93 * the argument
94 */
95 public void trace(String format, Object arg) {
96 if (logger.isLoggable(Level.FINEST)) {
97 FormattingTuple ft = MessageFormatter.format(format, arg);
98 log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable());
99 }
100 }
101
102 /**
103 * Log a message at level FINEST according to the specified format and
104 * arguments.
105 *
106 * <p>
107 * This form avoids superfluous object creation when the logger is disabled
108 * for the FINEST level.
109 * </p>
110 *
111 * @param format
112 * the format string
113 * @param arg1
114 * the first argument
115 * @param arg2
116 * the second argument
117 */
118 public void trace(String format, Object arg1, Object arg2) {
119 if (logger.isLoggable(Level.FINEST)) {
120 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
121 log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable());
122 }
123 }
124
125 /**
126 * Log a message at level FINEST according to the specified format and
127 * arguments.
128 *
129 * <p>
130 * This form avoids superfluous object creation when the logger is disabled
131 * for the FINEST level.
132 * </p>
133 *
134 * @param format
135 * the format string
136 * @param argArray
137 * an array of arguments
138 */
139 public void trace(String format, Object... argArray) {
140 if (logger.isLoggable(Level.FINEST)) {
141 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
142 log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable());
143 }
144 }
145
146 /**
147 * Log an exception (throwable) at level FINEST with an accompanying message.
148 *
149 * @param msg
150 * the message accompanying the exception
151 * @param t
152 * the exception (throwable) to log
153 */
154 public void trace(String msg, Throwable t) {
155 if (logger.isLoggable(Level.FINEST)) {
156 log(SELF, Level.FINEST, msg, t);
157 }
158 }
159
160 /**
161 * Is this logger instance enabled for the FINE level?
162 *
163 * @return True if this Logger is enabled for level FINE, false otherwise.
164 */
165 public boolean isDebugEnabled() {
166 return logger.isLoggable(Level.FINE);
167 }
168
169 /**
170 * Log a message object at level FINE.
171 *
172 * @param msg
173 * - the message object to be logged
174 */
175 public void debug(String msg) {
176 if (logger.isLoggable(Level.FINE)) {
177 log(SELF, Level.FINE, msg, null);
178 }
179 }
180
181 /**
182 * Log a message at level FINE according to the specified format and argument.
183 *
184 * <p>
185 * This form avoids superfluous object creation when the logger is disabled
186 * for level FINE.
187 * </p>
188 *
189 * @param format
190 * the format string
191 * @param arg
192 * the argument
193 */
194 public void debug(String format, Object arg) {
195 if (logger.isLoggable(Level.FINE)) {
196 FormattingTuple ft = MessageFormatter.format(format, arg);
197 log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable());
198 }
199 }
200
201 /**
202 * Log a message at level FINE according to the specified format and
203 * arguments.
204 *
205 * <p>
206 * This form avoids superfluous object creation when the logger is disabled
207 * for the FINE level.
208 * </p>
209 *
210 * @param format
211 * the format string
212 * @param arg1
213 * the first argument
214 * @param arg2
215 * the second argument
216 */
217 public void debug(String format, Object arg1, Object arg2) {
218 if (logger.isLoggable(Level.FINE)) {
219 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
220 log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable());
221 }
222 }
223
224 /**
225 * Log a message at level FINE according to the specified format and
226 * arguments.
227 *
228 * <p>
229 * This form avoids superfluous object creation when the logger is disabled
230 * for the FINE level.
231 * </p>
232 *
233 * @param format
234 * the format string
235 * @param argArray
236 * an array of arguments
237 */
238 public void debug(String format, Object... argArray) {
239 if (logger.isLoggable(Level.FINE)) {
240 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
241 log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable());
242 }
243 }
244
245 /**
246 * Log an exception (throwable) at level FINE with an accompanying message.
247 *
248 * @param msg
249 * the message accompanying the exception
250 * @param t
251 * the exception (throwable) to log
252 */
253 public void debug(String msg, Throwable t) {
254 if (logger.isLoggable(Level.FINE)) {
255 log(SELF, Level.FINE, msg, t);
256 }
257 }
258
259 /**
260 * Is this logger instance enabled for the INFO level?
261 *
262 * @return True if this Logger is enabled for the INFO level, false otherwise.
263 */
264 public boolean isInfoEnabled() {
265 return logger.isLoggable(Level.INFO);
266 }
267
268 /**
269 * Log a message object at the INFO level.
270 *
271 * @param msg
272 * - the message object to be logged
273 */
274 public void info(String msg) {
275 if (logger.isLoggable(Level.INFO)) {
276 log(SELF, Level.INFO, msg, null);
277 }
278 }
279
280 /**
281 * Log a message at level INFO according to the specified format and argument.
282 *
283 * <p>
284 * This form avoids superfluous object creation when the logger is disabled
285 * for the INFO level.
286 * </p>
287 *
288 * @param format
289 * the format string
290 * @param arg
291 * the argument
292 */
293 public void info(String format, Object arg) {
294 if (logger.isLoggable(Level.INFO)) {
295 FormattingTuple ft = MessageFormatter.format(format, arg);
296 log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable());
297 }
298 }
299
300 /**
301 * Log a message at the INFO level according to the specified format and
302 * arguments.
303 *
304 * <p>
305 * This form avoids superfluous object creation when the logger is disabled
306 * for the INFO level.
307 * </p>
308 *
309 * @param format
310 * the format string
311 * @param arg1
312 * the first argument
313 * @param arg2
314 * the second argument
315 */
316 public void info(String format, Object arg1, Object arg2) {
317 if (logger.isLoggable(Level.INFO)) {
318 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
319 log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable());
320 }
321 }
322
323 /**
324 * Log a message at level INFO according to the specified format and
325 * arguments.
326 *
327 * <p>
328 * This form avoids superfluous object creation when the logger is disabled
329 * for the INFO level.
330 * </p>
331 *
332 * @param format
333 * the format string
334 * @param argArray
335 * an array of arguments
336 */
337 public void info(String format, Object... argArray) {
338 if (logger.isLoggable(Level.INFO)) {
339 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
340 log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable());
341 }
342 }
343
344 /**
345 * Log an exception (throwable) at the INFO level with an accompanying
346 * message.
347 *
348 * @param msg
349 * the message accompanying the exception
350 * @param t
351 * the exception (throwable) to log
352 */
353 public void info(String msg, Throwable t) {
354 if (logger.isLoggable(Level.INFO)) {
355 log(SELF, Level.INFO, msg, t);
356 }
357 }
358
359 /**
360 * Is this logger instance enabled for the WARNING level?
361 *
362 * @return True if this Logger is enabled for the WARNING level, false
363 * otherwise.
364 */
365 public boolean isWarnEnabled() {
366 return logger.isLoggable(Level.WARNING);
367 }
368
369 /**
370 * Log a message object at the WARNING level.
371 *
372 * @param msg
373 * - the message object to be logged
374 */
375 public void warn(String msg) {
376 if (logger.isLoggable(Level.WARNING)) {
377 log(SELF, Level.WARNING, msg, null);
378 }
379 }
380
381 /**
382 * Log a message at the WARNING level according to the specified format and
383 * argument.
384 *
385 * <p>
386 * This form avoids superfluous object creation when the logger is disabled
387 * for the WARNING level.
388 * </p>
389 *
390 * @param format
391 * the format string
392 * @param arg
393 * the argument
394 */
395 public void warn(String format, Object arg) {
396 if (logger.isLoggable(Level.WARNING)) {
397 FormattingTuple ft = MessageFormatter.format(format, arg);
398 log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable());
399 }
400 }
401
402 /**
403 * Log a message at the WARNING level according to the specified format and
404 * arguments.
405 *
406 * <p>
407 * This form avoids superfluous object creation when the logger is disabled
408 * for the WARNING level.
409 * </p>
410 *
411 * @param format
412 * the format string
413 * @param arg1
414 * the first argument
415 * @param arg2
416 * the second argument
417 */
418 public void warn(String format, Object arg1, Object arg2) {
419 if (logger.isLoggable(Level.WARNING)) {
420 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
421 log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable());
422 }
423 }
424
425 /**
426 * Log a message at level WARNING according to the specified format and
427 * arguments.
428 *
429 * <p>
430 * This form avoids superfluous object creation when the logger is disabled
431 * for the WARNING level.
432 * </p>
433 *
434 * @param format
435 * the format string
436 * @param argArray
437 * an array of arguments
438 */
439 public void warn(String format, Object... argArray) {
440 if (logger.isLoggable(Level.WARNING)) {
441 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
442 log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable());
443 }
444 }
445
446 /**
447 * Log an exception (throwable) at the WARNING level with an accompanying
448 * message.
449 *
450 * @param msg
451 * the message accompanying the exception
452 * @param t
453 * the exception (throwable) to log
454 */
455 public void warn(String msg, Throwable t) {
456 if (logger.isLoggable(Level.WARNING)) {
457 log(SELF, Level.WARNING, msg, t);
458 }
459 }
460
461 /**
462 * Is this logger instance enabled for level SEVERE?
463 *
464 * @return True if this Logger is enabled for level SEVERE, false otherwise.
465 */
466 public boolean isErrorEnabled() {
467 return logger.isLoggable(Level.SEVERE);
468 }
469
470 /**
471 * Log a message object at the SEVERE level.
472 *
473 * @param msg
474 * - the message object to be logged
475 */
476 public void error(String msg) {
477 if (logger.isLoggable(Level.SEVERE)) {
478 log(SELF, Level.SEVERE, msg, null);
479 }
480 }
481
482 /**
483 * Log a message at the SEVERE level according to the specified format and
484 * argument.
485 *
486 * <p>
487 * This form avoids superfluous object creation when the logger is disabled
488 * for the SEVERE level.
489 * </p>
490 *
491 * @param format
492 * the format string
493 * @param arg
494 * the argument
495 */
496 public void error(String format, Object arg) {
497 if (logger.isLoggable(Level.SEVERE)) {
498 FormattingTuple ft = MessageFormatter.format(format, arg);
499 log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable());
500 }
501 }
502
503 /**
504 * Log a message at the SEVERE level according to the specified format and
505 * arguments.
506 *
507 * <p>
508 * This form avoids superfluous object creation when the logger is disabled
509 * for the SEVERE level.
510 * </p>
511 *
512 * @param format
513 * the format string
514 * @param arg1
515 * the first argument
516 * @param arg2
517 * the second argument
518 */
519 public void error(String format, Object arg1, Object arg2) {
520 if (logger.isLoggable(Level.SEVERE)) {
521 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
522 log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable());
523 }
524 }
525
526 /**
527 * Log a message at level SEVERE according to the specified format and
528 * arguments.
529 *
530 * <p>
531 * This form avoids superfluous object creation when the logger is disabled
532 * for the SEVERE level.
533 * </p>
534 *
535 * @param format
536 * the format string
537 * @param arguments
538 * an array of arguments
539 */
540 public void error(String format, Object... arguments) {
541 if (logger.isLoggable(Level.SEVERE)) {
542 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
543 log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable());
544 }
545 }
546
547 /**
548 * Log an exception (throwable) at the SEVERE level with an accompanying
549 * message.
550 *
551 * @param msg
552 * the message accompanying the exception
553 * @param t
554 * the exception (throwable) to log
555 */
556 public void error(String msg, Throwable t) {
557 if (logger.isLoggable(Level.SEVERE)) {
558 log(SELF, Level.SEVERE, msg, t);
559 }
560 }
561
562 /**
563 * Log the message at the specified level with the specified throwable if any.
564 * This method creates a LogRecord and fills in caller date before calling
565 * this instance's JDK14 logger.
566 *
567 * See bug report #13 for more details.
568 *
569 * @param level
570 * @param msg
571 * @param t
572 */
573 private void log(String callerFQCN, Level level, String msg, Throwable t) {
574 // millis and thread are filled by the constructor
575 LogRecord record = new LogRecord(level, msg);
576 record.setLoggerName(getName());
577 record.setThrown(t);
578 // Note: parameters in record are not set because SLF4J only
579 // supports a single formatting style
580 fillCallerData(callerFQCN, record);
581 logger.log(record);
582 }
583
584 static String SELF = JDK14LoggerAdapter.class.getName();
585 static String SUPER = MarkerIgnoringBase.class.getName();
586
587 /**
588 * Fill in caller data if possible.
589 *
590 * @param record
591 * The record to update
592 */
593 final private void fillCallerData(String callerFQCN, LogRecord record) {
594 StackTraceElement[] steArray = new Throwable().getStackTrace();
595
596 int selfIndex = -1;
597 for (int i = 0; i < steArray.length; i++) {
598 final String className = steArray[i].getClassName();
599 if (className.equals(callerFQCN) || className.equals(SUPER)) {
600 selfIndex = i;
601 break;
602 }
603 }
604
605 int found = -1;
606 for (int i = selfIndex + 1; i < steArray.length; i++) {
607 final String className = steArray[i].getClassName();
608 if (!(className.equals(callerFQCN) || className.equals(SUPER))) {
609 found = i;
610 break;
611 }
612 }
613
614 if (found != -1) {
615 StackTraceElement ste = steArray[found];
616 // setting the class name has the side effect of setting
617 // the needToInferCaller variable to false.
618 record.setSourceClassName(ste.getClassName());
619 record.setSourceMethodName(ste.getMethodName());
620 }
621 }
622
623 public void log(Marker marker, String callerFQCN, int level, String message, Object[] argArray, Throwable t) {
624 Level julLevel = slf4jLevelIntToJULLevel(level);
625 // the logger.isLoggable check avoids the unconditional
626 // construction of location data for disabled log
627 // statements. As of 2008-07-31, callers of this method
628 // do not perform this check. See also
629 // http://jira.qos.ch/browse/SLF4J-81
630 if (logger.isLoggable(julLevel)) {
631 log(callerFQCN, julLevel, message, t);
632 }
633 }
634
635 private Level slf4jLevelIntToJULLevel(int slf4jLevelInt) {
636 Level julLevel;
637 switch (slf4jLevelInt) {
638 case LocationAwareLogger.TRACE_INT:
639 julLevel = Level.FINEST;
640 break;
641 case LocationAwareLogger.DEBUG_INT:
642 julLevel = Level.FINE;
643 break;
644 case LocationAwareLogger.INFO_INT:
645 julLevel = Level.INFO;
646 break;
647 case LocationAwareLogger.WARN_INT:
648 julLevel = Level.WARNING;
649 break;
650 case LocationAwareLogger.ERROR_INT:
651 julLevel = Level.SEVERE;
652 break;
653 default:
654 throw new IllegalStateException("Level number " + slf4jLevelInt + " is not recognized.");
655 }
656 return julLevel;
657 }
658
659 /**
660 * @since 1.7.15
661 */
662 public void log(LoggingEvent event) {
663 Level julLevel = slf4jLevelIntToJULLevel(event.getLevel().toInt());
664 if (logger.isLoggable(julLevel)) {
665 LogRecord record = eventToRecord(event, julLevel);
666 logger.log(record);
667 }
668 }
669
670 private LogRecord eventToRecord(LoggingEvent event, Level julLevel) {
671 String format = event.getMessage();
672 Object[] arguments = event.getArgumentArray();
673 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
674 if (ft.getThrowable() != null && event.getThrowable() != null) {
675 throw new IllegalArgumentException("both last element in argument array and last argument are of type Throwable");
676 }
677
678 Throwable t = event.getThrowable();
679 if (ft.getThrowable() != null) {
680 t = ft.getThrowable();
681 throw new IllegalStateException("fix above code");
682 }
683
684 LogRecord record = new LogRecord(julLevel, ft.getMessage());
685 record.setLoggerName(event.getLoggerName());
686 record.setMillis(event.getTimeStamp());
687 record.setSourceClassName(EventConstants.NA_SUBST);
688 record.setSourceMethodName(EventConstants.NA_SUBST);
689
690 record.setThrown(t);
691 return record;
692 }
693 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.Logger;
27 import org.slf4j.ILoggerFactory;
28
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31
32 /**
33 * JDK14LoggerFactory is an implementation of {@link ILoggerFactory} returning
34 * the appropriately named {@link JDK14LoggerAdapter} instance.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class JDK14LoggerFactory implements ILoggerFactory {
39
40 // key: name (String), value: a JDK14LoggerAdapter;
41 ConcurrentMap<String, Logger> loggerMap;
42
43 public JDK14LoggerFactory() {
44 loggerMap = new ConcurrentHashMap<String, Logger>();
45 // ensure jul initialization. see SLF4J-359
46 // note that call to java.util.logging.LogManager.getLogManager() fails on the Google App Engine platform. See SLF4J-363
47 java.util.logging.Logger.getLogger("");
48 }
49
50 /*
51 * (non-Javadoc)
52 *
53 * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String)
54 */
55 public Logger getLogger(String name) {
56 // the root logger is called "" in JUL
57 if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) {
58 name = "";
59 }
60
61 Logger slf4jLogger = loggerMap.get(name);
62 if (slf4jLogger != null)
63 return slf4jLogger;
64 else {
65 java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(name);
66 Logger newInstance = new JDK14LoggerAdapter(julLogger);
67 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
68 return oldInstance == null ? newInstance : oldInstance;
69 }
70 }
71 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.Logger;
27 import org.slf4j.ILoggerFactory;
28
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31
32 /**
33 * JDK14LoggerFactory is an implementation of {@link ILoggerFactory} returning
34 * the appropriately named {@link JDK14LoggerAdapter} instance.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class JDK14LoggerFactory implements ILoggerFactory {
39
40 // key: name (String), value: a JDK14LoggerAdapter;
41 ConcurrentMap<String, Logger> loggerMap;
42
43 public JDK14LoggerFactory() {
44 loggerMap = new ConcurrentHashMap<String, Logger>();
45 // ensure jul initialization. see SLF4J-359
46 // note that call to java.util.logging.LogManager.getLogManager() fails on the Google App Engine platform. See SLF4J-363
47 java.util.logging.Logger.getLogger("");
48 }
49
50 /*
51 * (non-Javadoc)
52 *
53 * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String)
54 */
55 public Logger getLogger(String name) {
56 // the root logger is called "" in JUL
57 if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) {
58 name = "";
59 }
60
61 Logger slf4jLogger = loggerMap.get(name);
62 if (slf4jLogger != null)
63 return slf4jLogger;
64 else {
65 java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(name);
66 Logger newInstance = new JDK14LoggerAdapter(julLogger);
67 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
68 return oldInstance == null ? newInstance : oldInstance;
69 }
70 }
71 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class StaticLoggerBinder implements LoggerFactoryBinder {
37
38 /**
39 * The unique instance of this class.
40 *
41 */
42 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticLoggerBinder singleton
48 */
49 public static final StaticLoggerBinder getSingleton() {
50 return SINGLETON;
51 }
52
53 /**
54 * Declare the version of the SLF4J API this implementation is compiled against.
55 * The value of this field is modified with each major release.
56 */
57 // to avoid constant folding by the compiler, this field must *not* be final
58 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
59
60 private static final String loggerFactoryClassStr = org.slf4j.impl.JDK14LoggerFactory.class.getName();
61
62 /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method
63 * should always be the same object
64 */
65 private final ILoggerFactory loggerFactory;
66
67 private StaticLoggerBinder() {
68 // Note: JCL gets substituted at build time by an appropriate Ant task
69 loggerFactory = new org.slf4j.impl.JDK14LoggerFactory();
70 }
71
72 public ILoggerFactory getLoggerFactory() {
73 return loggerFactory;
74 }
75
76 public String getLoggerFactoryClassStr() {
77 return loggerFactoryClassStr;
78 }
79 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class StaticLoggerBinder implements LoggerFactoryBinder {
37
38 /**
39 * The unique instance of this class.
40 *
41 */
42 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticLoggerBinder singleton
48 */
49 public static final StaticLoggerBinder getSingleton() {
50 return SINGLETON;
51 }
52
53 /**
54 * Declare the version of the SLF4J API this implementation is compiled against.
55 * The value of this field is modified with each major release.
56 */
57 // to avoid constant folding by the compiler, this field must *not* be final
58 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
59
60 private static final String loggerFactoryClassStr = org.slf4j.impl.JDK14LoggerFactory.class.getName();
61
62 /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method
63 * should always be the same object
64 */
65 private final ILoggerFactory loggerFactory;
66
67 private StaticLoggerBinder() {
68 // Note: JCL gets substituted at build time by an appropriate Ant task
69 loggerFactory = new org.slf4j.impl.JDK14LoggerFactory();
70 }
71
72 public ILoggerFactory getLoggerFactory() {
73 return loggerFactory;
74 }
75
76 public String getLoggerFactoryClassStr() {
77 return loggerFactoryClassStr;
78 }
79 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.BasicMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link BasicMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticMDCBinder singleton
48 * @since 1.7.14
49 */
50 public static final StaticMDCBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Currently this method always returns an instance of
56 * {@link BasicMDCAdapter}.
57 */
58 public MDCAdapter getMDCA() {
59 // note that this method is invoked only from within the static initializer of
60 // the org.slf4j.MDC class.
61 return new BasicMDCAdapter();
62 }
63
64 public String getMDCAdapterClassStr() {
65 return BasicMDCAdapter.class.getName();
66 }
67 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.BasicMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link BasicMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticMDCBinder singleton
48 * @since 1.7.14
49 */
50 public static final StaticMDCBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Currently this method always returns an instance of
56 * {@link BasicMDCAdapter}.
57 */
58 public MDCAdapter getMDCA() {
59 // note that this method is invoked only from within the static initializer of
60 // the org.slf4j.MDC class.
61 return new BasicMDCAdapter();
62 }
63
64 public String getMDCAdapterClassStr() {
65 return BasicMDCAdapter.class.getName();
66 }
67 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Return the singleton of this class.
52 *
53 * @return the StaticMarkerBinder singleton
54 * @since 1.7.14
55 */
56 public static StaticMarkerBinder getSingleton() {
57 return SINGLETON;
58 }
59
60 /**
61 * Currently this method always returns an instance of
62 * {@link BasicMarkerFactory}.
63 */
64 public IMarkerFactory getMarkerFactory() {
65 return markerFactory;
66 }
67
68 /**
69 * Currently, this method returns the class name of
70 * {@link BasicMarkerFactory}.
71 */
72 public String getMarkerFactoryClassStr() {
73 return BasicMarkerFactory.class.getName();
74 }
75
76 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Return the singleton of this class.
52 *
53 * @return the StaticMarkerBinder singleton
54 * @since 1.7.14
55 */
56 public static StaticMarkerBinder getSingleton() {
57 return SINGLETON;
58 }
59
60 /**
61 * Currently this method always returns an instance of
62 * {@link BasicMarkerFactory}.
63 */
64 public IMarkerFactory getMarkerFactory() {
65 return markerFactory;
66 }
67
68 /**
69 * Currently, this method returns the class name of
70 * {@link BasicMarkerFactory}.
71 */
72 public String getMarkerFactoryClassStr() {
73 return BasicMarkerFactory.class.getName();
74 }
75
76 }
0 Implementation-Title: slf4j-jdk14
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.jdk14
3 Bundle-Name: slf4j-jdk14
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},
8 org.slf4j.spi;version=${parsedVersion.osgiVersion},
9 org.slf4j.helpers;version=${parsedVersion.osgiVersion},
10 org.slf4j.event;version=${parsedVersion.osgiVersion}
0 Implementation-Title: slf4j-jdk14
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.jdk14
3 Bundle-Name: slf4j-jdk14
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},
8 org.slf4j.spi;version=${parsedVersion.osgiVersion},
9 org.slf4j.helpers;version=${parsedVersion.osgiVersion},
10 org.slf4j.event;version=${parsedVersion.osgiVersion}
1111 Fragment-Host: slf4j.api
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import org.junit.After;
27 import org.junit.Assert;
28 import org.junit.Before;
29 import org.junit.Test;
30
31 import java.util.ArrayList;
32 import java.util.List;
33 import java.util.logging.Handler;
34 import java.util.logging.Level;
35 import java.util.logging.LogRecord;
36
37 import static org.junit.Assert.assertNotNull;
38 import static org.junit.Assert.assertNull;
39 import static org.junit.Assert.assertEquals;
40 import static org.junit.Assert.fail;
41
42 /**
43 * Test whether invoking the SLF4J API causes problems or not.
44 *
45 * @author Ceki Gulcu
46 */
47 public class InvocationTest {
48
49 Level oldLevel;
50 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
51
52 ListHandler listHandler = new ListHandler();
53
54 @Before
55 public void setUp() throws Exception {
56 oldLevel = root.getLevel();
57 root.setLevel(Level.FINE);
58 // removeAllHandlers(root);
59 root.addHandler(listHandler);
60 }
61
62 @After
63 public void tearDown() throws Exception {
64 root.setLevel(oldLevel);
65 removeListHandlers(root);
66 }
67
68 @Test
69 public void test1() {
70 Logger logger = LoggerFactory.getLogger("test1");
71 logger.debug("Hello world.");
72 assertLogMessage("Hello world.", 0);
73 }
74
75 @Test
76 public void verifyMessageFormatting() {
77 Integer i1 = new Integer(1);
78 Integer i2 = new Integer(2);
79 Integer i3 = new Integer(3);
80 Exception e = new Exception("This is a test exception.");
81 Logger logger = LoggerFactory.getLogger("test2");
82
83 int index = 0;
84 logger.debug("Hello world");
85 assertLogMessage("Hello world", index++);
86
87 logger.debug("Hello world {}", i1);
88 assertLogMessage("Hello world " + i1, index++);
89
90 logger.debug("val={} val={}", i1, i2);
91 assertLogMessage("val=1 val=2", index++);
92
93 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
94 assertLogMessage("val=1 val=2 val=3", index++);
95
96 logger.debug("Hello world 2", e);
97 assertLogMessage("Hello world 2", index);
98 assertException(e.getClass(), index++);
99 logger.info("Hello world 2.");
100
101 logger.warn("Hello world 3.");
102 logger.warn("Hello world 3", e);
103
104 logger.error("Hello world 4.");
105 logger.error("Hello world {}", new Integer(3));
106 logger.error("Hello world 4.", e);
107 }
108
109 @Test
110 public void testNull() {
111 Logger logger = LoggerFactory.getLogger("testNull");
112 logger.debug(null);
113 logger.info(null);
114 logger.warn(null);
115 logger.error(null);
116
117 Exception e = new Exception("This is a test exception.");
118 logger.debug(null, e);
119 logger.info(null, e);
120 logger.warn(null, e);
121 logger.error(null, e);
122 }
123
124 @Test
125 public void testMarker() {
126 Logger logger = LoggerFactory.getLogger("testMarker");
127 Marker blue = MarkerFactory.getMarker("BLUE");
128 logger.debug(blue, "hello");
129 logger.info(blue, "hello");
130 logger.warn(blue, "hello");
131 logger.error(blue, "hello");
132
133 logger.debug(blue, "hello {}", "world");
134 logger.info(blue, "hello {}", "world");
135 logger.warn(blue, "hello {}", "world");
136 logger.error(blue, "hello {}", "world");
137
138 logger.debug(blue, "hello {} and {} ", "world", "universe");
139 logger.info(blue, "hello {} and {} ", "world", "universe");
140 logger.warn(blue, "hello {} and {} ", "world", "universe");
141 logger.error(blue, "hello {} and {} ", "world", "universe");
142 }
143
144 @Test
145 public void testMDC() {
146 MDC.put("k", "v");
147 assertNotNull(MDC.get("k"));
148 assertEquals("v", MDC.get("k"));
149
150 MDC.remove("k");
151 assertNull(MDC.get("k"));
152
153 MDC.put("k1", "v1");
154 assertEquals("v1", MDC.get("k1"));
155 MDC.clear();
156 assertNull(MDC.get("k1"));
157
158 try {
159 MDC.put(null, "x");
160 fail("null keys are invalid");
161 } catch (IllegalArgumentException e) {
162 }
163 }
164
165 private void assertLogMessage(String expected, int index) {
166 LogRecord logRecord = listHandler.recordList.get(index);
167 Assert.assertNotNull(logRecord);
168 assertEquals(expected, logRecord.getMessage());
169 }
170
171 private void assertException(Class<? extends Throwable> exceptionType, int index) {
172 LogRecord logRecord = listHandler.recordList.get(index);
173 Assert.assertNotNull(logRecord);
174 assertEquals(exceptionType, logRecord.getThrown().getClass());
175 }
176
177 void removeListHandlers(java.util.logging.Logger logger) {
178 Handler[] handlers = logger.getHandlers();
179 for (Handler h : handlers) {
180 if (h instanceof ListHandler)
181 logger.removeHandler(h);
182 }
183 }
184
185 static private class ListHandler extends java.util.logging.Handler {
186
187 List<LogRecord> recordList = new ArrayList<LogRecord>();
188
189 @Override
190 public void publish(LogRecord record) {
191 recordList.add(record);
192 }
193
194 @Override
195 public void flush() {
196 }
197
198 @Override
199 public void close() throws SecurityException {
200 }
201 }
202 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import org.junit.After;
27 import org.junit.Assert;
28 import org.junit.Before;
29 import org.junit.Test;
30
31 import java.util.ArrayList;
32 import java.util.List;
33 import java.util.logging.Handler;
34 import java.util.logging.Level;
35 import java.util.logging.LogRecord;
36
37 import static org.junit.Assert.assertNotNull;
38 import static org.junit.Assert.assertNull;
39 import static org.junit.Assert.assertEquals;
40 import static org.junit.Assert.fail;
41
42 /**
43 * Test whether invoking the SLF4J API causes problems or not.
44 *
45 * @author Ceki Gulcu
46 */
47 public class InvocationTest {
48
49 Level oldLevel;
50 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
51
52 ListHandler listHandler = new ListHandler();
53
54 @Before
55 public void setUp() throws Exception {
56 oldLevel = root.getLevel();
57 root.setLevel(Level.FINE);
58 // removeAllHandlers(root);
59 root.addHandler(listHandler);
60 }
61
62 @After
63 public void tearDown() throws Exception {
64 root.setLevel(oldLevel);
65 removeListHandlers(root);
66 }
67
68 @Test
69 public void test1() {
70 Logger logger = LoggerFactory.getLogger("test1");
71 logger.debug("Hello world.");
72 assertLogMessage("Hello world.", 0);
73 }
74
75 @Test
76 public void verifyMessageFormatting() {
77 Integer i1 = new Integer(1);
78 Integer i2 = new Integer(2);
79 Integer i3 = new Integer(3);
80 Exception e = new Exception("This is a test exception.");
81 Logger logger = LoggerFactory.getLogger("test2");
82
83 int index = 0;
84 logger.debug("Hello world");
85 assertLogMessage("Hello world", index++);
86
87 logger.debug("Hello world {}", i1);
88 assertLogMessage("Hello world " + i1, index++);
89
90 logger.debug("val={} val={}", i1, i2);
91 assertLogMessage("val=1 val=2", index++);
92
93 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
94 assertLogMessage("val=1 val=2 val=3", index++);
95
96 logger.debug("Hello world 2", e);
97 assertLogMessage("Hello world 2", index);
98 assertException(e.getClass(), index++);
99 logger.info("Hello world 2.");
100
101 logger.warn("Hello world 3.");
102 logger.warn("Hello world 3", e);
103
104 logger.error("Hello world 4.");
105 logger.error("Hello world {}", new Integer(3));
106 logger.error("Hello world 4.", e);
107 }
108
109 @Test
110 public void testNull() {
111 Logger logger = LoggerFactory.getLogger("testNull");
112 logger.debug(null);
113 logger.info(null);
114 logger.warn(null);
115 logger.error(null);
116
117 Exception e = new Exception("This is a test exception.");
118 logger.debug(null, e);
119 logger.info(null, e);
120 logger.warn(null, e);
121 logger.error(null, e);
122 }
123
124 @Test
125 public void testMarker() {
126 Logger logger = LoggerFactory.getLogger("testMarker");
127 Marker blue = MarkerFactory.getMarker("BLUE");
128 logger.debug(blue, "hello");
129 logger.info(blue, "hello");
130 logger.warn(blue, "hello");
131 logger.error(blue, "hello");
132
133 logger.debug(blue, "hello {}", "world");
134 logger.info(blue, "hello {}", "world");
135 logger.warn(blue, "hello {}", "world");
136 logger.error(blue, "hello {}", "world");
137
138 logger.debug(blue, "hello {} and {} ", "world", "universe");
139 logger.info(blue, "hello {} and {} ", "world", "universe");
140 logger.warn(blue, "hello {} and {} ", "world", "universe");
141 logger.error(blue, "hello {} and {} ", "world", "universe");
142 }
143
144 @Test
145 public void testMDC() {
146 MDC.put("k", "v");
147 assertNotNull(MDC.get("k"));
148 assertEquals("v", MDC.get("k"));
149
150 MDC.remove("k");
151 assertNull(MDC.get("k"));
152
153 MDC.put("k1", "v1");
154 assertEquals("v1", MDC.get("k1"));
155 MDC.clear();
156 assertNull(MDC.get("k1"));
157
158 try {
159 MDC.put(null, "x");
160 fail("null keys are invalid");
161 } catch (IllegalArgumentException e) {
162 }
163 }
164
165 private void assertLogMessage(String expected, int index) {
166 LogRecord logRecord = listHandler.recordList.get(index);
167 Assert.assertNotNull(logRecord);
168 assertEquals(expected, logRecord.getMessage());
169 }
170
171 private void assertException(Class<? extends Throwable> exceptionType, int index) {
172 LogRecord logRecord = listHandler.recordList.get(index);
173 Assert.assertNotNull(logRecord);
174 assertEquals(exceptionType, logRecord.getThrown().getClass());
175 }
176
177 void removeListHandlers(java.util.logging.Logger logger) {
178 Handler[] handlers = logger.getHandlers();
179 for (Handler h : handlers) {
180 if (h instanceof ListHandler)
181 logger.removeHandler(h);
182 }
183 }
184
185 static private class ListHandler extends java.util.logging.Handler {
186
187 List<LogRecord> recordList = new ArrayList<LogRecord>();
188
189 @Override
190 public void publish(LogRecord record) {
191 recordList.add(record);
192 }
193
194 @Override
195 public void flush() {
196 }
197
198 @Override
199 public void close() throws SecurityException {
200 }
201 }
202 }
0 package org.slf4j;
1
2 public class LoggerFactoryFriend {
3 static public void reset() {
4 LoggerFactory.reset();
5 }
6 }
0 package org.slf4j;
1
2 public class LoggerFactoryFriend {
3 static public void reset() {
4 LoggerFactory.reset();
5 }
6 }
0 package org.slf4j.helpers;
1
2 import java.util.concurrent.atomic.AtomicLong;
3 import java.util.logging.Handler;
4 import java.util.logging.LogRecord;
5
6 public class CountingHandler extends Handler {
7
8 final AtomicLong eventCount = new AtomicLong(0);
9
10 @Override
11 public void publish(LogRecord record) {
12 eventCount.getAndIncrement();
13 }
14
15 @Override
16 public void flush() {
17 }
18
19 @Override
20 public void close() throws SecurityException {
21 }
22
23 }
0 package org.slf4j.helpers;
1
2 import java.util.concurrent.atomic.AtomicLong;
3 import java.util.logging.Handler;
4 import java.util.logging.LogRecord;
5
6 public class CountingHandler extends Handler {
7
8 final AtomicLong eventCount = new AtomicLong(0);
9
10 @Override
11 public void publish(LogRecord record) {
12 eventCount.getAndIncrement();
13 }
14
15 @Override
16 public void flush() {
17 }
18
19 @Override
20 public void close() throws SecurityException {
21 }
22
23 }
0 /**
1 * Copyright (c) 2004-2016 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import static org.junit.Assert.fail;
27
28 import java.util.logging.Handler;
29
30 import org.junit.After;
31 import org.junit.Before;
32
33 public class JDK14MultithreadedInitializationTest extends MultithreadedInitializationTest {
34
35 java.util.logging.Logger julRootLogger = java.util.logging.Logger.getLogger("");
36 java.util.logging.Logger julOrgLogger = java.util.logging.Logger.getLogger("org");
37
38 @Before
39 public void addRecordingHandler() {
40 System.out.println("THREAD_COUNT=" + THREAD_COUNT);
41 removeAllHandlers(julRootLogger);
42 removeAllHandlers(julOrgLogger);
43 julOrgLogger.addHandler(new CountingHandler());
44 }
45
46 private void removeAllHandlers(java.util.logging.Logger logger) {
47 Handler[] handlers = logger.getHandlers();
48 for (int i = 0; i < handlers.length; i++) {
49 logger.removeHandler(handlers[i]);
50 }
51 }
52
53 @After
54 public void tearDown() throws Exception {
55 removeAllHandlers(julOrgLogger);
56 }
57
58 protected long getRecordedEventCount() {
59 CountingHandler ra = findRecordingHandler();
60 if (ra == null) {
61 fail("failed to fing RecordingHandler");
62 }
63 return ra.eventCount.get();
64 }
65
66 private CountingHandler findRecordingHandler() {
67 Handler[] handlers = julOrgLogger.getHandlers();
68 for (Handler h : handlers) {
69 if (h instanceof CountingHandler)
70 return (CountingHandler) h;
71 }
72 return null;
73 }
74
75 }
0 /**
1 * Copyright (c) 2004-2016 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import static org.junit.Assert.fail;
27
28 import java.util.logging.Handler;
29
30 import org.junit.After;
31 import org.junit.Before;
32
33 public class JDK14MultithreadedInitializationTest extends MultithreadedInitializationTest {
34
35 java.util.logging.Logger julRootLogger = java.util.logging.Logger.getLogger("");
36 java.util.logging.Logger julOrgLogger = java.util.logging.Logger.getLogger("org");
37
38 @Before
39 public void addRecordingHandler() {
40 System.out.println("THREAD_COUNT=" + THREAD_COUNT);
41 removeAllHandlers(julRootLogger);
42 removeAllHandlers(julOrgLogger);
43 julOrgLogger.addHandler(new CountingHandler());
44 }
45
46 private void removeAllHandlers(java.util.logging.Logger logger) {
47 Handler[] handlers = logger.getHandlers();
48 for (int i = 0; i < handlers.length; i++) {
49 logger.removeHandler(handlers[i]);
50 }
51 }
52
53 @After
54 public void tearDown() throws Exception {
55 removeAllHandlers(julOrgLogger);
56 }
57
58 protected long getRecordedEventCount() {
59 CountingHandler ra = findRecordingHandler();
60 if (ra == null) {
61 fail("failed to fing RecordingHandler");
62 }
63 return ra.eventCount.get();
64 }
65
66 private CountingHandler findRecordingHandler() {
67 Handler[] handlers = julOrgLogger.getHandlers();
68 for (Handler h : handlers) {
69 if (h instanceof CountingHandler)
70 return (CountingHandler) h;
71 }
72 return null;
73 }
74
75 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import static org.junit.Assert.assertNotNull;
27
28 import java.util.Random;
29 import java.util.logging.Handler;
30 import java.util.logging.LogRecord;
31 import java.util.logging.Logger;
32
33 import org.junit.After;
34 import org.junit.Before;
35 import org.junit.Test;
36
37 public class JDK14AdapterLoggerNameTest {
38 private MockHandler mockHandler;
39 static Random random = new Random(System.currentTimeMillis());
40 long diff = random.nextInt(10000);
41 String loggerName = "JDK14AdapterLoggerNameTest"+diff;
42
43 Logger logger = Logger.getLogger(loggerName);
44
45 @Before
46 public void setUp() throws Exception {
47 Logger logger = Logger.getLogger(loggerName);
48 addMockHandler(logger);
49 }
50
51
52
53 @After
54 public void tearDown() throws Exception {
55 removeHandlers(Logger.getLogger(loggerName));
56 }
57
58 @Test
59 public void testLoggerNameUsingJdkLogging() throws Exception {
60 logger.info("test message");
61 assertCorrectLoggerName();
62 }
63
64 @Test
65 public void testLoggerNameUsingSlf4j() throws Exception {
66 JDK14LoggerFactory factory = new JDK14LoggerFactory();
67 org.slf4j.Logger logger = factory.getLogger(loggerName);
68 logger.info("test message");
69 assertCorrectLoggerName();
70 }
71
72 private void addMockHandler(Logger logger) {
73 mockHandler = new MockHandler();
74 removeHandlers(logger);
75 logger.addHandler(mockHandler);
76 }
77
78 private void removeHandlers(Logger logger) {
79 logger.setUseParentHandlers(false);
80 Handler[] handlers = logger.getHandlers();
81 for (int i = 0; i < handlers.length; i++) {
82 logger.removeHandler(handlers[i]);
83 }
84 }
85
86 private void assertCorrectLoggerName() {
87 assertNotNull("no log record", mockHandler.record);
88 assertNotNull("missing logger name", mockHandler.record.getLoggerName());
89 }
90
91 private class MockHandler extends java.util.logging.Handler {
92 public LogRecord record;
93
94 public void close() throws SecurityException {
95 }
96
97 public void flush() {
98 }
99
100 public void publish(LogRecord record) {
101 this.record = record;
102 }
103
104 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import static org.junit.Assert.assertNotNull;
27
28 import java.util.Random;
29 import java.util.logging.Handler;
30 import java.util.logging.LogRecord;
31 import java.util.logging.Logger;
32
33 import org.junit.After;
34 import org.junit.Before;
35 import org.junit.Test;
36
37 public class JDK14AdapterLoggerNameTest {
38 private MockHandler mockHandler;
39 static Random random = new Random(System.currentTimeMillis());
40 long diff = random.nextInt(10000);
41 String loggerName = "JDK14AdapterLoggerNameTest"+diff;
42
43 Logger logger = Logger.getLogger(loggerName);
44
45 @Before
46 public void setUp() throws Exception {
47 Logger logger = Logger.getLogger(loggerName);
48 addMockHandler(logger);
49 }
50
51
52
53 @After
54 public void tearDown() throws Exception {
55 removeHandlers(Logger.getLogger(loggerName));
56 }
57
58 @Test
59 public void testLoggerNameUsingJdkLogging() throws Exception {
60 logger.info("test message");
61 assertCorrectLoggerName();
62 }
63
64 @Test
65 public void testLoggerNameUsingSlf4j() throws Exception {
66 JDK14LoggerFactory factory = new JDK14LoggerFactory();
67 org.slf4j.Logger logger = factory.getLogger(loggerName);
68 logger.info("test message");
69 assertCorrectLoggerName();
70 }
71
72 private void addMockHandler(Logger logger) {
73 mockHandler = new MockHandler();
74 removeHandlers(logger);
75 logger.addHandler(mockHandler);
76 }
77
78 private void removeHandlers(Logger logger) {
79 logger.setUseParentHandlers(false);
80 Handler[] handlers = logger.getHandlers();
81 for (int i = 0; i < handlers.length; i++) {
82 logger.removeHandler(handlers[i]);
83 }
84 }
85
86 private void assertCorrectLoggerName() {
87 assertNotNull("no log record", mockHandler.record);
88 assertNotNull("missing logger name", mockHandler.record.getLoggerName());
89 }
90
91 private class MockHandler extends java.util.logging.Handler {
92 public LogRecord record;
93
94 public void close() throws SecurityException {
95 }
96
97 public void flush() {
98 }
99
100 public void publish(LogRecord record) {
101 this.record = record;
102 }
103
104 }
105105 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.junit.Ignore;
27 import org.junit.Test;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.slf4j.helpers.BogoPerf;
31
32 @Ignore
33 public class PerfTest {
34
35 static long REFERENCE_BIPS = 9000;
36
37 @Test
38 public void issue63() {
39
40 int LEN = 1000 * 1000 * 10;
41 debugLoop(LEN); // warm up
42 double avg = debugLoop(LEN);
43 long referencePerf = 93;
44 BogoPerf.assertDuration(avg, referencePerf, REFERENCE_BIPS);
45
46 // when the code is guarded by a logger.isLoggable condition,
47 // duration is about 16 *micro*seconds for 1000 iterations
48 // when it is not guarded the figure is 90 milliseconds,
49 // i.e. a ration of 1 to 5000
50 }
51
52 double debugLoop(int len) {
53 Logger logger = LoggerFactory.getLogger(PerfTest.class);
54 long start = System.currentTimeMillis();
55 for (int i = 0; i < len; i++) {
56 logger.debug("hello");
57 }
58
59 long end = System.currentTimeMillis();
60
61 long duration = end - start;
62 return duration;
63 }
64
65 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.junit.Ignore;
27 import org.junit.Test;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.slf4j.helpers.BogoPerf;
31
32 @Ignore
33 public class PerfTest {
34
35 static long REFERENCE_BIPS = 9000;
36
37 @Test
38 public void issue63() {
39
40 int LEN = 1000 * 1000 * 10;
41 debugLoop(LEN); // warm up
42 double avg = debugLoop(LEN);
43 long referencePerf = 93;
44 BogoPerf.assertDuration(avg, referencePerf, REFERENCE_BIPS);
45
46 // when the code is guarded by a logger.isLoggable condition,
47 // duration is about 16 *micro*seconds for 1000 iterations
48 // when it is not guarded the figure is 90 milliseconds,
49 // i.e. a ration of 1 to 5000
50 }
51
52 double debugLoop(int len) {
53 Logger logger = LoggerFactory.getLogger(PerfTest.class);
54 long start = System.currentTimeMillis();
55 for (int i = 0; i < len; i++) {
56 logger.debug("hello");
57 }
58
59 long end = System.currentTimeMillis();
60
61 long duration = end - start;
62 return duration;
63 }
64
65 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.issue;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.ByteArrayOutputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.ObjectInputStream;
31 import java.io.ObjectOutputStream;
32 import java.io.Serializable;
33
34 import static org.junit.Assert.assertNotNull;
35
36 import org.junit.Test;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41 * See http://jira.qos.ch/browse/SLF4J-252
42 * @author Thorbjorn Ravn Andersen
43 */
44 public class LoggerSerializationTest {
45
46 static class LoggerHolder implements Serializable {
47 private static final long serialVersionUID = 1L;
48
49 private Logger log = LoggerFactory.getLogger(LoggerHolder.class);
50
51 public String toString() {
52 return "log=" + getLog();
53 }
54
55 public Logger getLog() {
56 return log;
57 }
58 }
59
60 @Test
61 public void testCanLoggerBeSerialized() throws IOException, ClassNotFoundException {
62
63 LoggerHolder lh1 = new LoggerHolder();
64
65 ByteArrayOutputStream baos = new ByteArrayOutputStream();
66 ObjectOutputStream out = new ObjectOutputStream(baos);
67 out.writeObject(lh1);
68 out.close();
69
70 lh1 = null;
71
72 byte[] serializedLoggerHolder = baos.toByteArray();
73
74 InputStream is = new ByteArrayInputStream(serializedLoggerHolder);
75 ObjectInputStream in = new ObjectInputStream(is);
76 LoggerHolder lh2 = (LoggerHolder) in.readObject();
77
78 assertNotNull(lh2);
79 assertNotNull(lh2.getLog());
80 lh2.getLog().info("You must see this message as a log message");
81 }
82
83 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.issue;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.ByteArrayOutputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.ObjectInputStream;
31 import java.io.ObjectOutputStream;
32 import java.io.Serializable;
33
34 import static org.junit.Assert.assertNotNull;
35
36 import org.junit.Test;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41 * See http://jira.qos.ch/browse/SLF4J-252
42 * @author Thorbjorn Ravn Andersen
43 */
44 public class LoggerSerializationTest {
45
46 static class LoggerHolder implements Serializable {
47 private static final long serialVersionUID = 1L;
48
49 private Logger log = LoggerFactory.getLogger(LoggerHolder.class);
50
51 public String toString() {
52 return "log=" + getLog();
53 }
54
55 public Logger getLog() {
56 return log;
57 }
58 }
59
60 @Test
61 public void testCanLoggerBeSerialized() throws IOException, ClassNotFoundException {
62
63 LoggerHolder lh1 = new LoggerHolder();
64
65 ByteArrayOutputStream baos = new ByteArrayOutputStream();
66 ObjectOutputStream out = new ObjectOutputStream(baos);
67 out.writeObject(lh1);
68 out.close();
69
70 lh1 = null;
71
72 byte[] serializedLoggerHolder = baos.toByteArray();
73
74 InputStream is = new ByteArrayInputStream(serializedLoggerHolder);
75 ObjectInputStream in = new ObjectInputStream(is);
76 LoggerHolder lh2 = (LoggerHolder) in.readObject();
77
78 assertNotNull(lh2);
79 assertNotNull(lh2.getLog());
80 lh2.getLog().info("You must see this message as a log message");
81 }
82
83 }
0 Copyright (c) 2004-2007 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>slf4j-log4j12</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J LOG4J-12 Binding</name>
16 <description>SLF4J LOG4J-12 Binding</description>
17 <url>http://www.slf4j.org</url>
18
19 <dependencies>
20 <dependency>
21 <groupId>org.slf4j</groupId>
22 <artifactId>slf4j-api</artifactId>
23 </dependency>
24
25 <dependency>
26 <groupId>log4j</groupId>
27 <artifactId>log4j</artifactId>
28 </dependency>
29
30 <dependency>
31 <groupId>org.slf4j</groupId>
32 <artifactId>slf4j-api</artifactId>
33 <type>test-jar</type>
34 <version>${project.version}</version>
35 <scope>test</scope>
36 </dependency>
37 </dependencies>
38
39 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>slf4j-log4j12</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J LOG4J-12 Binding</name>
16 <description>SLF4J LOG4J-12 Binding</description>
17 <url>http://www.slf4j.org</url>
18
19 <dependencies>
20 <dependency>
21 <groupId>org.slf4j</groupId>
22 <artifactId>slf4j-api</artifactId>
23 </dependency>
24
25 <dependency>
26 <groupId>log4j</groupId>
27 <artifactId>log4j</artifactId>
28 </dependency>
29
30 <dependency>
31 <groupId>org.slf4j</groupId>
32 <artifactId>slf4j-api</artifactId>
33 <type>test-jar</type>
34 <version>${project.version}</version>
35 <scope>test</scope>
36 </dependency>
37 </dependencies>
38
39
40 </project>
0 package org.apache.log4j;
1
2 import java.lang.reflect.Field;
3 import java.lang.reflect.Method;
4
5 import org.apache.log4j.helpers.ThreadLocalMap;
6
7 public class MDCFriend {
8
9 public static void fixForJava9() {
10 if (MDC.mdc.tlm == null) {
11 MDC.mdc.tlm = new ThreadLocalMap();
12 MDC.mdc.java1 = false;
13 setRemoveMethod(MDC.mdc);
14 }
15
16 }
17
18 private static void setRemoveMethod(MDC mdc) {
19 try {
20 Method removeMethod = ThreadLocal.class.getMethod("remove");
21 Field removeMethodField = MDC.class.getDeclaredField("removeMethod");
22 removeMethodField.setAccessible(true);
23 removeMethodField.set(mdc, removeMethod);
24 } catch (NoSuchMethodException e) {
25 } catch (SecurityException e) {
26 } catch (NoSuchFieldException e) {
27 } catch (IllegalArgumentException e) {
28 } catch (IllegalAccessException e) {
29 }
30
31 }
32 }
0 package org.apache.log4j;
1
2 import java.lang.reflect.Field;
3 import java.lang.reflect.Method;
4
5 import org.apache.log4j.helpers.ThreadLocalMap;
6
7 public class MDCFriend {
8
9 public static void fixForJava9() {
10 if (MDC.mdc.tlm == null) {
11 MDC.mdc.tlm = new ThreadLocalMap();
12 MDC.mdc.java1 = false;
13 setRemoveMethod(MDC.mdc);
14 }
15
16 }
17
18 private static void setRemoveMethod(MDC mdc) {
19 try {
20 Method removeMethod = ThreadLocal.class.getMethod("remove");
21 Field removeMethodField = MDC.class.getDeclaredField("removeMethod");
22 removeMethodField.setAccessible(true);
23 removeMethodField.set(mdc, removeMethod);
24 } catch (NoSuchMethodException e) {
25 } catch (SecurityException e) {
26 } catch (NoSuchFieldException e) {
27 } catch (IllegalArgumentException e) {
28 } catch (IllegalAccessException e) {
29 }
30
31 }
32 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import static org.slf4j.event.EventConstants.NA_SUBST;
27
28 import java.io.Serializable;
29
30 import org.apache.log4j.Level;
31 import org.apache.log4j.spi.LocationInfo;
32 import org.apache.log4j.spi.ThrowableInformation;
33 import org.slf4j.Logger;
34 import org.slf4j.Marker;
35 import org.slf4j.event.LoggingEvent;
36 import org.slf4j.helpers.FormattingTuple;
37 import org.slf4j.helpers.MarkerIgnoringBase;
38 import org.slf4j.helpers.MessageFormatter;
39 import org.slf4j.spi.LocationAwareLogger;
40
41 /**
42 * A wrapper over {@link org.apache.log4j.Logger org.apache.log4j.Logger} in
43 * conforming to the {@link Logger} interface.
44 *
45 * <p>
46 * Note that the logging levels mentioned in this class refer to those defined
47 * in the <a
48 * href="http://logging.apache.org/log4j/docs/api/org/apache/log4j/Level.html">
49 * <code>org.apache.log4j.Level</code></a> class.
50 *
51 * <p>
52 * The TRACE level was introduced in log4j version 1.2.12. In order to avoid
53 * crashing the host application, in the case the log4j version in use predates
54 * 1.2.12, the TRACE level will be mapped as DEBUG. See also <a
55 * href="http://jira.qos.ch/browse/SLF4J-59">SLF4J-59</a>.
56 *
57 * @author Ceki G&uuml;lc&uuml;
58 */
59 public final class Log4jLoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger, Serializable {
60
61 private static final long serialVersionUID = 6182834493563598289L;
62
63 final transient org.apache.log4j.Logger logger;
64
65 /**
66 * Following the pattern discussed in pages 162 through 168 of "The complete
67 * log4j manual".
68 */
69 final static String FQCN = Log4jLoggerAdapter.class.getName();
70
71 // Does the log4j version in use recognize the TRACE level?
72 // The trace level was introduced in log4j 1.2.12.
73 final boolean traceCapable;
74
75 // WARN: Log4jLoggerAdapter constructor should have only package access so
76 // that
77 // only Log4jLoggerFactory be able to create one.
78 Log4jLoggerAdapter(org.apache.log4j.Logger logger) {
79 this.logger = logger;
80 this.name = logger.getName();
81 traceCapable = isTraceCapable();
82 }
83
84 private boolean isTraceCapable() {
85 try {
86 logger.isTraceEnabled();
87 return true;
88 } catch (NoSuchMethodError e) {
89 return false;
90 }
91 }
92
93 /**
94 * Is this logger instance enabled for the TRACE level?
95 *
96 * @return True if this Logger is enabled for level TRACE, false otherwise.
97 */
98 public boolean isTraceEnabled() {
99 if (traceCapable) {
100 return logger.isTraceEnabled();
101 } else {
102 return logger.isDebugEnabled();
103 }
104 }
105
106 /**
107 * Log a message object at level TRACE.
108 *
109 * @param msg
110 * - the message object to be logged
111 */
112 public void trace(String msg) {
113 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, null);
114 }
115
116 /**
117 * Log a message at level TRACE according to the specified format and
118 * argument.
119 *
120 * <p>
121 * This form avoids superfluous object creation when the logger is disabled
122 * for level TRACE.
123 * </p>
124 *
125 * @param format
126 * the format string
127 * @param arg
128 * the argument
129 */
130 public void trace(String format, Object arg) {
131 if (isTraceEnabled()) {
132 FormattingTuple ft = MessageFormatter.format(format, arg);
133 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable());
134 }
135 }
136
137 /**
138 * Log a message at level TRACE according to the specified format and
139 * arguments.
140 *
141 * <p>
142 * This form avoids superfluous object creation when the logger is disabled
143 * for the TRACE level.
144 * </p>
145 *
146 * @param format
147 * the format string
148 * @param arg1
149 * the first argument
150 * @param arg2
151 * the second argument
152 */
153 public void trace(String format, Object arg1, Object arg2) {
154 if (isTraceEnabled()) {
155 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
156 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable());
157 }
158 }
159
160 /**
161 * Log a message at level TRACE according to the specified format and
162 * arguments.
163 *
164 * <p>
165 * This form avoids superfluous object creation when the logger is disabled
166 * for the TRACE level.
167 * </p>
168 *
169 * @param format
170 * the format string
171 * @param arguments
172 * an array of arguments
173 */
174 public void trace(String format, Object... arguments) {
175 if (isTraceEnabled()) {
176 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
177 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable());
178 }
179 }
180
181 /**
182 * Log an exception (throwable) at level TRACE with an accompanying message.
183 *
184 * @param msg
185 * the message accompanying the exception
186 * @param t
187 * the exception (throwable) to log
188 */
189 public void trace(String msg, Throwable t) {
190 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, t);
191 }
192
193 /**
194 * Is this logger instance enabled for the DEBUG level?
195 *
196 * @return True if this Logger is enabled for level DEBUG, false otherwise.
197 */
198 public boolean isDebugEnabled() {
199 return logger.isDebugEnabled();
200 }
201
202 /**
203 * Log a message object at level DEBUG.
204 *
205 * @param msg
206 * - the message object to be logged
207 */
208 public void debug(String msg) {
209 logger.log(FQCN, Level.DEBUG, msg, null);
210 }
211
212 /**
213 * Log a message at level DEBUG according to the specified format and
214 * argument.
215 *
216 * <p>
217 * This form avoids superfluous object creation when the logger is disabled
218 * for level DEBUG.
219 * </p>
220 *
221 * @param format
222 * the format string
223 * @param arg
224 * the argument
225 */
226 public void debug(String format, Object arg) {
227 if (logger.isDebugEnabled()) {
228 FormattingTuple ft = MessageFormatter.format(format, arg);
229 logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
230 }
231 }
232
233 /**
234 * Log a message at level DEBUG according to the specified format and
235 * arguments.
236 *
237 * <p>
238 * This form avoids superfluous object creation when the logger is disabled
239 * for the DEBUG level.
240 * </p>
241 *
242 * @param format
243 * the format string
244 * @param arg1
245 * the first argument
246 * @param arg2
247 * the second argument
248 */
249 public void debug(String format, Object arg1, Object arg2) {
250 if (logger.isDebugEnabled()) {
251 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
252 logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
253 }
254 }
255
256 /**
257 * Log a message at level DEBUG according to the specified format and
258 * arguments.
259 *
260 * <p>
261 * This form avoids superfluous object creation when the logger is disabled
262 * for the DEBUG level.
263 * </p>
264 *
265 * @param format
266 * the format string
267 * @param arguments an array of arguments
268 */
269 public void debug(String format, Object... arguments) {
270 if (logger.isDebugEnabled()) {
271 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
272 logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
273 }
274 }
275
276 /**
277 * Log an exception (throwable) at level DEBUG with an accompanying message.
278 *
279 * @param msg
280 * the message accompanying the exception
281 * @param t
282 * the exception (throwable) to log
283 */
284 public void debug(String msg, Throwable t) {
285 logger.log(FQCN, Level.DEBUG, msg, t);
286 }
287
288 /**
289 * Is this logger instance enabled for the INFO level?
290 *
291 * @return True if this Logger is enabled for the INFO level, false otherwise.
292 */
293 public boolean isInfoEnabled() {
294 return logger.isInfoEnabled();
295 }
296
297 /**
298 * Log a message object at the INFO level.
299 *
300 * @param msg
301 * - the message object to be logged
302 */
303 public void info(String msg) {
304 logger.log(FQCN, Level.INFO, msg, null);
305 }
306
307 /**
308 * Log a message at level INFO according to the specified format and argument.
309 *
310 * <p>
311 * This form avoids superfluous object creation when the logger is disabled
312 * for the INFO level.
313 * </p>
314 *
315 * @param format
316 * the format string
317 * @param arg
318 * the argument
319 */
320 public void info(String format, Object arg) {
321 if (logger.isInfoEnabled()) {
322 FormattingTuple ft = MessageFormatter.format(format, arg);
323 logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
324 }
325 }
326
327 /**
328 * Log a message at the INFO level according to the specified format and
329 * arguments.
330 *
331 * <p>
332 * This form avoids superfluous object creation when the logger is disabled
333 * for the INFO level.
334 * </p>
335 *
336 * @param format
337 * the format string
338 * @param arg1
339 * the first argument
340 * @param arg2
341 * the second argument
342 */
343 public void info(String format, Object arg1, Object arg2) {
344 if (logger.isInfoEnabled()) {
345 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
346 logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
347 }
348 }
349
350 /**
351 * Log a message at level INFO according to the specified format and
352 * arguments.
353 *
354 * <p>
355 * This form avoids superfluous object creation when the logger is disabled
356 * for the INFO level.
357 * </p>
358 *
359 * @param format
360 * the format string
361 * @param argArray
362 * an array of arguments
363 */
364 public void info(String format, Object... argArray) {
365 if (logger.isInfoEnabled()) {
366 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
367 logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
368 }
369 }
370
371 /**
372 * Log an exception (throwable) at the INFO level with an accompanying
373 * message.
374 *
375 * @param msg
376 * the message accompanying the exception
377 * @param t
378 * the exception (throwable) to log
379 */
380 public void info(String msg, Throwable t) {
381 logger.log(FQCN, Level.INFO, msg, t);
382 }
383
384 /**
385 * Is this logger instance enabled for the WARN level?
386 *
387 * @return True if this Logger is enabled for the WARN level, false otherwise.
388 */
389 public boolean isWarnEnabled() {
390 return logger.isEnabledFor(Level.WARN);
391 }
392
393 /**
394 * Log a message object at the WARN level.
395 *
396 * @param msg
397 * - the message object to be logged
398 */
399 public void warn(String msg) {
400 logger.log(FQCN, Level.WARN, msg, null);
401 }
402
403 /**
404 * Log a message at the WARN level according to the specified format and
405 * argument.
406 *
407 * <p>
408 * This form avoids superfluous object creation when the logger is disabled
409 * for the WARN level.
410 * </p>
411 *
412 * @param format
413 * the format string
414 * @param arg
415 * the argument
416 */
417 public void warn(String format, Object arg) {
418 if (logger.isEnabledFor(Level.WARN)) {
419 FormattingTuple ft = MessageFormatter.format(format, arg);
420 logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
421 }
422 }
423
424 /**
425 * Log a message at the WARN level according to the specified format and
426 * arguments.
427 *
428 * <p>
429 * This form avoids superfluous object creation when the logger is disabled
430 * for the WARN level.
431 * </p>
432 *
433 * @param format
434 * the format string
435 * @param arg1
436 * the first argument
437 * @param arg2
438 * the second argument
439 */
440 public void warn(String format, Object arg1, Object arg2) {
441 if (logger.isEnabledFor(Level.WARN)) {
442 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
443 logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
444 }
445 }
446
447 /**
448 * Log a message at level WARN according to the specified format and
449 * arguments.
450 *
451 * <p>
452 * This form avoids superfluous object creation when the logger is disabled
453 * for the WARN level.
454 * </p>
455 *
456 * @param format
457 * the format string
458 * @param argArray
459 * an array of arguments
460 */
461 public void warn(String format, Object... argArray) {
462 if (logger.isEnabledFor(Level.WARN)) {
463 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
464 logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
465 }
466 }
467
468 /**
469 * Log an exception (throwable) at the WARN level with an accompanying
470 * message.
471 *
472 * @param msg
473 * the message accompanying the exception
474 * @param t
475 * the exception (throwable) to log
476 */
477 public void warn(String msg, Throwable t) {
478 logger.log(FQCN, Level.WARN, msg, t);
479 }
480
481 /**
482 * Is this logger instance enabled for level ERROR?
483 *
484 * @return True if this Logger is enabled for level ERROR, false otherwise.
485 */
486 public boolean isErrorEnabled() {
487 return logger.isEnabledFor(Level.ERROR);
488 }
489
490 /**
491 * Log a message object at the ERROR level.
492 *
493 * @param msg
494 * - the message object to be logged
495 */
496 public void error(String msg) {
497 logger.log(FQCN, Level.ERROR, msg, null);
498 }
499
500 /**
501 * Log a message at the ERROR level according to the specified format and
502 * argument.
503 *
504 * <p>
505 * This form avoids superfluous object creation when the logger is disabled
506 * for the ERROR level.
507 * </p>
508 *
509 * @param format
510 * the format string
511 * @param arg
512 * the argument
513 */
514 public void error(String format, Object arg) {
515 if (logger.isEnabledFor(Level.ERROR)) {
516 FormattingTuple ft = MessageFormatter.format(format, arg);
517 logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
518 }
519 }
520
521 /**
522 * Log a message at the ERROR level according to the specified format and
523 * arguments.
524 *
525 * <p>
526 * This form avoids superfluous object creation when the logger is disabled
527 * for the ERROR level.
528 * </p>
529 *
530 * @param format
531 * the format string
532 * @param arg1
533 * the first argument
534 * @param arg2
535 * the second argument
536 */
537 public void error(String format, Object arg1, Object arg2) {
538 if (logger.isEnabledFor(Level.ERROR)) {
539 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
540 logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
541 }
542 }
543
544 /**
545 * Log a message at level ERROR according to the specified format and
546 * arguments.
547 *
548 * <p>
549 * This form avoids superfluous object creation when the logger is disabled
550 * for the ERROR level.
551 * </p>
552 *
553 * @param format
554 * the format string
555 * @param argArray
556 * an array of arguments
557 */
558 public void error(String format, Object... argArray) {
559 if (logger.isEnabledFor(Level.ERROR)) {
560 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
561 logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
562 }
563 }
564
565 /**
566 * Log an exception (throwable) at the ERROR level with an accompanying
567 * message.
568 *
569 * @param msg
570 * the message accompanying the exception
571 * @param t
572 * the exception (throwable) to log
573 */
574 public void error(String msg, Throwable t) {
575 logger.log(FQCN, Level.ERROR, msg, t);
576 }
577
578 public void log(Marker marker, String callerFQCN, int level, String msg, Object[] argArray, Throwable t) {
579 Level log4jLevel = toLog4jLevel(level);
580 logger.log(callerFQCN, log4jLevel, msg, t);
581 }
582
583 private Level toLog4jLevel(int level) {
584 Level log4jLevel;
585 switch (level) {
586 case LocationAwareLogger.TRACE_INT:
587 log4jLevel = traceCapable ? Level.TRACE : Level.DEBUG;
588 break;
589 case LocationAwareLogger.DEBUG_INT:
590 log4jLevel = Level.DEBUG;
591 break;
592 case LocationAwareLogger.INFO_INT:
593 log4jLevel = Level.INFO;
594 break;
595 case LocationAwareLogger.WARN_INT:
596 log4jLevel = Level.WARN;
597 break;
598 case LocationAwareLogger.ERROR_INT:
599 log4jLevel = Level.ERROR;
600 break;
601 default:
602 throw new IllegalStateException("Level number " + level + " is not recognized.");
603 }
604 return log4jLevel;
605 }
606
607 public void log(LoggingEvent event) {
608 Level log4jLevel = toLog4jLevel(event.getLevel().toInt());
609 if (!logger.isEnabledFor(log4jLevel))
610 return;
611
612 org.apache.log4j.spi.LoggingEvent log4jevent = toLog4jEvent(event, log4jLevel);
613 logger.callAppenders(log4jevent);
614
615 }
616
617 private org.apache.log4j.spi.LoggingEvent toLog4jEvent(LoggingEvent event, Level log4jLevel) {
618
619 FormattingTuple ft = MessageFormatter.format(event.getMessage(), event.getArgumentArray(), event.getThrowable());
620
621 LocationInfo locationInfo = new LocationInfo(NA_SUBST, NA_SUBST, NA_SUBST, "0");
622
623 ThrowableInformation ti = null;
624 Throwable t = ft.getThrowable();
625 if (t != null)
626 ti = new ThrowableInformation(t);
627
628 org.apache.log4j.spi.LoggingEvent log4jEvent = new org.apache.log4j.spi.LoggingEvent(FQCN, logger, event.getTimeStamp(), log4jLevel, ft.getMessage(),
629 event.getThreadName(), ti, null, locationInfo, null);
630
631 return log4jEvent;
632 }
633
634 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import static org.slf4j.event.EventConstants.NA_SUBST;
27
28 import java.io.Serializable;
29
30 import org.apache.log4j.Level;
31 import org.apache.log4j.spi.LocationInfo;
32 import org.apache.log4j.spi.ThrowableInformation;
33 import org.slf4j.Logger;
34 import org.slf4j.Marker;
35 import org.slf4j.event.LoggingEvent;
36 import org.slf4j.helpers.FormattingTuple;
37 import org.slf4j.helpers.MarkerIgnoringBase;
38 import org.slf4j.helpers.MessageFormatter;
39 import org.slf4j.spi.LocationAwareLogger;
40
41 /**
42 * A wrapper over {@link org.apache.log4j.Logger org.apache.log4j.Logger} in
43 * conforming to the {@link Logger} interface.
44 *
45 * <p>
46 * Note that the logging levels mentioned in this class refer to those defined
47 * in the <a
48 * href="http://logging.apache.org/log4j/docs/api/org/apache/log4j/Level.html">
49 * <code>org.apache.log4j.Level</code></a> class.
50 *
51 * <p>
52 * The TRACE level was introduced in log4j version 1.2.12. In order to avoid
53 * crashing the host application, in the case the log4j version in use predates
54 * 1.2.12, the TRACE level will be mapped as DEBUG. See also <a
55 * href="http://jira.qos.ch/browse/SLF4J-59">SLF4J-59</a>.
56 *
57 * @author Ceki G&uuml;lc&uuml;
58 */
59 public final class Log4jLoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger, Serializable {
60
61 private static final long serialVersionUID = 6182834493563598289L;
62
63 final transient org.apache.log4j.Logger logger;
64
65 /**
66 * Following the pattern discussed in pages 162 through 168 of "The complete
67 * log4j manual".
68 */
69 final static String FQCN = Log4jLoggerAdapter.class.getName();
70
71 // Does the log4j version in use recognize the TRACE level?
72 // The trace level was introduced in log4j 1.2.12.
73 final boolean traceCapable;
74
75 // WARN: Log4jLoggerAdapter constructor should have only package access so
76 // that
77 // only Log4jLoggerFactory be able to create one.
78 Log4jLoggerAdapter(org.apache.log4j.Logger logger) {
79 this.logger = logger;
80 this.name = logger.getName();
81 traceCapable = isTraceCapable();
82 }
83
84 private boolean isTraceCapable() {
85 try {
86 logger.isTraceEnabled();
87 return true;
88 } catch (NoSuchMethodError e) {
89 return false;
90 }
91 }
92
93 /**
94 * Is this logger instance enabled for the TRACE level?
95 *
96 * @return True if this Logger is enabled for level TRACE, false otherwise.
97 */
98 public boolean isTraceEnabled() {
99 if (traceCapable) {
100 return logger.isTraceEnabled();
101 } else {
102 return logger.isDebugEnabled();
103 }
104 }
105
106 /**
107 * Log a message object at level TRACE.
108 *
109 * @param msg
110 * - the message object to be logged
111 */
112 public void trace(String msg) {
113 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, null);
114 }
115
116 /**
117 * Log a message at level TRACE according to the specified format and
118 * argument.
119 *
120 * <p>
121 * This form avoids superfluous object creation when the logger is disabled
122 * for level TRACE.
123 * </p>
124 *
125 * @param format
126 * the format string
127 * @param arg
128 * the argument
129 */
130 public void trace(String format, Object arg) {
131 if (isTraceEnabled()) {
132 FormattingTuple ft = MessageFormatter.format(format, arg);
133 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable());
134 }
135 }
136
137 /**
138 * Log a message at level TRACE according to the specified format and
139 * arguments.
140 *
141 * <p>
142 * This form avoids superfluous object creation when the logger is disabled
143 * for the TRACE level.
144 * </p>
145 *
146 * @param format
147 * the format string
148 * @param arg1
149 * the first argument
150 * @param arg2
151 * the second argument
152 */
153 public void trace(String format, Object arg1, Object arg2) {
154 if (isTraceEnabled()) {
155 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
156 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable());
157 }
158 }
159
160 /**
161 * Log a message at level TRACE according to the specified format and
162 * arguments.
163 *
164 * <p>
165 * This form avoids superfluous object creation when the logger is disabled
166 * for the TRACE level.
167 * </p>
168 *
169 * @param format
170 * the format string
171 * @param arguments
172 * an array of arguments
173 */
174 public void trace(String format, Object... arguments) {
175 if (isTraceEnabled()) {
176 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
177 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable());
178 }
179 }
180
181 /**
182 * Log an exception (throwable) at level TRACE with an accompanying message.
183 *
184 * @param msg
185 * the message accompanying the exception
186 * @param t
187 * the exception (throwable) to log
188 */
189 public void trace(String msg, Throwable t) {
190 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, t);
191 }
192
193 /**
194 * Is this logger instance enabled for the DEBUG level?
195 *
196 * @return True if this Logger is enabled for level DEBUG, false otherwise.
197 */
198 public boolean isDebugEnabled() {
199 return logger.isDebugEnabled();
200 }
201
202 /**
203 * Log a message object at level DEBUG.
204 *
205 * @param msg
206 * - the message object to be logged
207 */
208 public void debug(String msg) {
209 logger.log(FQCN, Level.DEBUG, msg, null);
210 }
211
212 /**
213 * Log a message at level DEBUG according to the specified format and
214 * argument.
215 *
216 * <p>
217 * This form avoids superfluous object creation when the logger is disabled
218 * for level DEBUG.
219 * </p>
220 *
221 * @param format
222 * the format string
223 * @param arg
224 * the argument
225 */
226 public void debug(String format, Object arg) {
227 if (logger.isDebugEnabled()) {
228 FormattingTuple ft = MessageFormatter.format(format, arg);
229 logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
230 }
231 }
232
233 /**
234 * Log a message at level DEBUG according to the specified format and
235 * arguments.
236 *
237 * <p>
238 * This form avoids superfluous object creation when the logger is disabled
239 * for the DEBUG level.
240 * </p>
241 *
242 * @param format
243 * the format string
244 * @param arg1
245 * the first argument
246 * @param arg2
247 * the second argument
248 */
249 public void debug(String format, Object arg1, Object arg2) {
250 if (logger.isDebugEnabled()) {
251 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
252 logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
253 }
254 }
255
256 /**
257 * Log a message at level DEBUG according to the specified format and
258 * arguments.
259 *
260 * <p>
261 * This form avoids superfluous object creation when the logger is disabled
262 * for the DEBUG level.
263 * </p>
264 *
265 * @param format
266 * the format string
267 * @param arguments an array of arguments
268 */
269 public void debug(String format, Object... arguments) {
270 if (logger.isDebugEnabled()) {
271 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
272 logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
273 }
274 }
275
276 /**
277 * Log an exception (throwable) at level DEBUG with an accompanying message.
278 *
279 * @param msg
280 * the message accompanying the exception
281 * @param t
282 * the exception (throwable) to log
283 */
284 public void debug(String msg, Throwable t) {
285 logger.log(FQCN, Level.DEBUG, msg, t);
286 }
287
288 /**
289 * Is this logger instance enabled for the INFO level?
290 *
291 * @return True if this Logger is enabled for the INFO level, false otherwise.
292 */
293 public boolean isInfoEnabled() {
294 return logger.isInfoEnabled();
295 }
296
297 /**
298 * Log a message object at the INFO level.
299 *
300 * @param msg
301 * - the message object to be logged
302 */
303 public void info(String msg) {
304 logger.log(FQCN, Level.INFO, msg, null);
305 }
306
307 /**
308 * Log a message at level INFO according to the specified format and argument.
309 *
310 * <p>
311 * This form avoids superfluous object creation when the logger is disabled
312 * for the INFO level.
313 * </p>
314 *
315 * @param format
316 * the format string
317 * @param arg
318 * the argument
319 */
320 public void info(String format, Object arg) {
321 if (logger.isInfoEnabled()) {
322 FormattingTuple ft = MessageFormatter.format(format, arg);
323 logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
324 }
325 }
326
327 /**
328 * Log a message at the INFO level according to the specified format and
329 * arguments.
330 *
331 * <p>
332 * This form avoids superfluous object creation when the logger is disabled
333 * for the INFO level.
334 * </p>
335 *
336 * @param format
337 * the format string
338 * @param arg1
339 * the first argument
340 * @param arg2
341 * the second argument
342 */
343 public void info(String format, Object arg1, Object arg2) {
344 if (logger.isInfoEnabled()) {
345 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
346 logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
347 }
348 }
349
350 /**
351 * Log a message at level INFO according to the specified format and
352 * arguments.
353 *
354 * <p>
355 * This form avoids superfluous object creation when the logger is disabled
356 * for the INFO level.
357 * </p>
358 *
359 * @param format
360 * the format string
361 * @param argArray
362 * an array of arguments
363 */
364 public void info(String format, Object... argArray) {
365 if (logger.isInfoEnabled()) {
366 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
367 logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
368 }
369 }
370
371 /**
372 * Log an exception (throwable) at the INFO level with an accompanying
373 * message.
374 *
375 * @param msg
376 * the message accompanying the exception
377 * @param t
378 * the exception (throwable) to log
379 */
380 public void info(String msg, Throwable t) {
381 logger.log(FQCN, Level.INFO, msg, t);
382 }
383
384 /**
385 * Is this logger instance enabled for the WARN level?
386 *
387 * @return True if this Logger is enabled for the WARN level, false otherwise.
388 */
389 public boolean isWarnEnabled() {
390 return logger.isEnabledFor(Level.WARN);
391 }
392
393 /**
394 * Log a message object at the WARN level.
395 *
396 * @param msg
397 * - the message object to be logged
398 */
399 public void warn(String msg) {
400 logger.log(FQCN, Level.WARN, msg, null);
401 }
402
403 /**
404 * Log a message at the WARN level according to the specified format and
405 * argument.
406 *
407 * <p>
408 * This form avoids superfluous object creation when the logger is disabled
409 * for the WARN level.
410 * </p>
411 *
412 * @param format
413 * the format string
414 * @param arg
415 * the argument
416 */
417 public void warn(String format, Object arg) {
418 if (logger.isEnabledFor(Level.WARN)) {
419 FormattingTuple ft = MessageFormatter.format(format, arg);
420 logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
421 }
422 }
423
424 /**
425 * Log a message at the WARN level according to the specified format and
426 * arguments.
427 *
428 * <p>
429 * This form avoids superfluous object creation when the logger is disabled
430 * for the WARN level.
431 * </p>
432 *
433 * @param format
434 * the format string
435 * @param arg1
436 * the first argument
437 * @param arg2
438 * the second argument
439 */
440 public void warn(String format, Object arg1, Object arg2) {
441 if (logger.isEnabledFor(Level.WARN)) {
442 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
443 logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
444 }
445 }
446
447 /**
448 * Log a message at level WARN according to the specified format and
449 * arguments.
450 *
451 * <p>
452 * This form avoids superfluous object creation when the logger is disabled
453 * for the WARN level.
454 * </p>
455 *
456 * @param format
457 * the format string
458 * @param argArray
459 * an array of arguments
460 */
461 public void warn(String format, Object... argArray) {
462 if (logger.isEnabledFor(Level.WARN)) {
463 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
464 logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
465 }
466 }
467
468 /**
469 * Log an exception (throwable) at the WARN level with an accompanying
470 * message.
471 *
472 * @param msg
473 * the message accompanying the exception
474 * @param t
475 * the exception (throwable) to log
476 */
477 public void warn(String msg, Throwable t) {
478 logger.log(FQCN, Level.WARN, msg, t);
479 }
480
481 /**
482 * Is this logger instance enabled for level ERROR?
483 *
484 * @return True if this Logger is enabled for level ERROR, false otherwise.
485 */
486 public boolean isErrorEnabled() {
487 return logger.isEnabledFor(Level.ERROR);
488 }
489
490 /**
491 * Log a message object at the ERROR level.
492 *
493 * @param msg
494 * - the message object to be logged
495 */
496 public void error(String msg) {
497 logger.log(FQCN, Level.ERROR, msg, null);
498 }
499
500 /**
501 * Log a message at the ERROR level according to the specified format and
502 * argument.
503 *
504 * <p>
505 * This form avoids superfluous object creation when the logger is disabled
506 * for the ERROR level.
507 * </p>
508 *
509 * @param format
510 * the format string
511 * @param arg
512 * the argument
513 */
514 public void error(String format, Object arg) {
515 if (logger.isEnabledFor(Level.ERROR)) {
516 FormattingTuple ft = MessageFormatter.format(format, arg);
517 logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
518 }
519 }
520
521 /**
522 * Log a message at the ERROR level according to the specified format and
523 * arguments.
524 *
525 * <p>
526 * This form avoids superfluous object creation when the logger is disabled
527 * for the ERROR level.
528 * </p>
529 *
530 * @param format
531 * the format string
532 * @param arg1
533 * the first argument
534 * @param arg2
535 * the second argument
536 */
537 public void error(String format, Object arg1, Object arg2) {
538 if (logger.isEnabledFor(Level.ERROR)) {
539 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
540 logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
541 }
542 }
543
544 /**
545 * Log a message at level ERROR according to the specified format and
546 * arguments.
547 *
548 * <p>
549 * This form avoids superfluous object creation when the logger is disabled
550 * for the ERROR level.
551 * </p>
552 *
553 * @param format
554 * the format string
555 * @param argArray
556 * an array of arguments
557 */
558 public void error(String format, Object... argArray) {
559 if (logger.isEnabledFor(Level.ERROR)) {
560 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
561 logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
562 }
563 }
564
565 /**
566 * Log an exception (throwable) at the ERROR level with an accompanying
567 * message.
568 *
569 * @param msg
570 * the message accompanying the exception
571 * @param t
572 * the exception (throwable) to log
573 */
574 public void error(String msg, Throwable t) {
575 logger.log(FQCN, Level.ERROR, msg, t);
576 }
577
578 public void log(Marker marker, String callerFQCN, int level, String msg, Object[] argArray, Throwable t) {
579 Level log4jLevel = toLog4jLevel(level);
580 logger.log(callerFQCN, log4jLevel, msg, t);
581 }
582
583 private Level toLog4jLevel(int level) {
584 Level log4jLevel;
585 switch (level) {
586 case LocationAwareLogger.TRACE_INT:
587 log4jLevel = traceCapable ? Level.TRACE : Level.DEBUG;
588 break;
589 case LocationAwareLogger.DEBUG_INT:
590 log4jLevel = Level.DEBUG;
591 break;
592 case LocationAwareLogger.INFO_INT:
593 log4jLevel = Level.INFO;
594 break;
595 case LocationAwareLogger.WARN_INT:
596 log4jLevel = Level.WARN;
597 break;
598 case LocationAwareLogger.ERROR_INT:
599 log4jLevel = Level.ERROR;
600 break;
601 default:
602 throw new IllegalStateException("Level number " + level + " is not recognized.");
603 }
604 return log4jLevel;
605 }
606
607 public void log(LoggingEvent event) {
608 Level log4jLevel = toLog4jLevel(event.getLevel().toInt());
609 if (!logger.isEnabledFor(log4jLevel))
610 return;
611
612 org.apache.log4j.spi.LoggingEvent log4jevent = toLog4jEvent(event, log4jLevel);
613 logger.callAppenders(log4jevent);
614
615 }
616
617 private org.apache.log4j.spi.LoggingEvent toLog4jEvent(LoggingEvent event, Level log4jLevel) {
618
619 FormattingTuple ft = MessageFormatter.format(event.getMessage(), event.getArgumentArray(), event.getThrowable());
620
621 LocationInfo locationInfo = new LocationInfo(NA_SUBST, NA_SUBST, NA_SUBST, "0");
622
623 ThrowableInformation ti = null;
624 Throwable t = ft.getThrowable();
625 if (t != null)
626 ti = new ThrowableInformation(t);
627
628 org.apache.log4j.spi.LoggingEvent log4jEvent = new org.apache.log4j.spi.LoggingEvent(FQCN, logger, event.getTimeStamp(), log4jLevel, ft.getMessage(),
629 event.getThreadName(), ti, null, locationInfo, null);
630
631 return log4jEvent;
632 }
633
634 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.apache.log4j.LogManager;
30 import org.slf4j.ILoggerFactory;
31 import org.slf4j.Logger;
32 import org.slf4j.helpers.Util;
33
34 /**
35 * Log4jLoggerFactory is an implementation of {@link ILoggerFactory} returning
36 * the appropriate named {@link Log4jLoggerAdapter} instance.
37 *
38 * @author Ceki G&uuml;lc&uuml;
39 */
40 public class Log4jLoggerFactory implements ILoggerFactory {
41
42 private static final String LOG4J_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#log4jDelegationLoop";
43
44 // check for delegation loops
45 static {
46 try {
47 Class.forName("org.apache.log4j.Log4jLoggerFactory");
48 String part1 = "Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the class path, preempting StackOverflowError. ";
49 String part2 = "See also " + LOG4J_DELEGATION_LOOP_URL + " for more details.";
50
51 Util.report(part1);
52 Util.report(part2);
53 throw new IllegalStateException(part1 + part2);
54 } catch (ClassNotFoundException e) {
55 // this is the good case
56 }
57 }
58
59 // key: name (String), value: a Log4jLoggerAdapter;
60 ConcurrentMap<String, Logger> loggerMap;
61
62 public Log4jLoggerFactory() {
63 loggerMap = new ConcurrentHashMap<String, Logger>();
64 // force log4j to initialize
65 org.apache.log4j.LogManager.getRootLogger();
66 }
67
68 /*
69 * (non-Javadoc)
70 *
71 * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String)
72 */
73 public Logger getLogger(String name) {
74 Logger slf4jLogger = loggerMap.get(name);
75 if (slf4jLogger != null) {
76 return slf4jLogger;
77 } else {
78 org.apache.log4j.Logger log4jLogger;
79 if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME))
80 log4jLogger = LogManager.getRootLogger();
81 else
82 log4jLogger = LogManager.getLogger(name);
83
84 Logger newInstance = new Log4jLoggerAdapter(log4jLogger);
85 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
86 return oldInstance == null ? newInstance : oldInstance;
87 }
88 }
89 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.apache.log4j.LogManager;
30 import org.slf4j.ILoggerFactory;
31 import org.slf4j.Logger;
32 import org.slf4j.helpers.Util;
33
34 /**
35 * Log4jLoggerFactory is an implementation of {@link ILoggerFactory} returning
36 * the appropriate named {@link Log4jLoggerAdapter} instance.
37 *
38 * @author Ceki G&uuml;lc&uuml;
39 */
40 public class Log4jLoggerFactory implements ILoggerFactory {
41
42 private static final String LOG4J_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#log4jDelegationLoop";
43
44 // check for delegation loops
45 static {
46 try {
47 Class.forName("org.apache.log4j.Log4jLoggerFactory");
48 String part1 = "Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the class path, preempting StackOverflowError. ";
49 String part2 = "See also " + LOG4J_DELEGATION_LOOP_URL + " for more details.";
50
51 Util.report(part1);
52 Util.report(part2);
53 throw new IllegalStateException(part1 + part2);
54 } catch (ClassNotFoundException e) {
55 // this is the good case
56 }
57 }
58
59 // key: name (String), value: a Log4jLoggerAdapter;
60 ConcurrentMap<String, Logger> loggerMap;
61
62 public Log4jLoggerFactory() {
63 loggerMap = new ConcurrentHashMap<String, Logger>();
64 // force log4j to initialize
65 org.apache.log4j.LogManager.getRootLogger();
66 }
67
68 /*
69 * (non-Javadoc)
70 *
71 * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String)
72 */
73 public Logger getLogger(String name) {
74 Logger slf4jLogger = loggerMap.get(name);
75 if (slf4jLogger != null) {
76 return slf4jLogger;
77 } else {
78 org.apache.log4j.Logger log4jLogger;
79 if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME))
80 log4jLogger = LogManager.getRootLogger();
81 else
82 log4jLogger = LogManager.getLogger(name);
83
84 Logger newInstance = new Log4jLoggerAdapter(log4jLogger);
85 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
86 return oldInstance == null ? newInstance : oldInstance;
87 }
88 }
89 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.Map;
29
30 import org.apache.log4j.MDCFriend;
31 import org.slf4j.spi.MDCAdapter;
32
33 public class Log4jMDCAdapter implements MDCAdapter {
34
35 static {
36 if (VersionUtil.getJavaMajorVersion() >= 9) {
37 MDCFriend.fixForJava9();
38 }
39 }
40
41 public void clear() {
42 @SuppressWarnings("rawtypes")
43 Map map = org.apache.log4j.MDC.getContext();
44 if (map != null) {
45 map.clear();
46 }
47 }
48
49 public String get(String key) {
50 return (String) org.apache.log4j.MDC.get(key);
51 }
52
53 /**
54 * Put a context value (the <code>val</code> parameter) as identified with
55 * the <code>key</code> parameter into the current thread's context map. The
56 * <code>key</code> parameter cannot be null. Log4j does <em>not</em>
57 * support null for the <code>val</code> parameter.
58 *
59 * <p>
60 * This method delegates all work to log4j's MDC.
61 *
62 * @throws IllegalArgumentException
63 * in case the "key" or <b>"val"</b> parameter is null
64 */
65 public void put(String key, String val) {
66 org.apache.log4j.MDC.put(key, val);
67 }
68
69 public void remove(String key) {
70 org.apache.log4j.MDC.remove(key);
71 }
72
73 @SuppressWarnings({ "rawtypes", "unchecked" })
74 public Map getCopyOfContextMap() {
75 Map old = org.apache.log4j.MDC.getContext();
76 if (old != null) {
77 return new HashMap(old);
78 } else {
79 return null;
80 }
81 }
82
83 @SuppressWarnings({ "rawtypes", "unchecked" })
84 public void setContextMap(Map contextMap) {
85 Map old = org.apache.log4j.MDC.getContext();
86 if (old == null) {
87 Iterator entrySetIterator = contextMap.entrySet().iterator();
88 while (entrySetIterator.hasNext()) {
89 Map.Entry mapEntry = (Map.Entry) entrySetIterator.next();
90 org.apache.log4j.MDC.put((String) mapEntry.getKey(), mapEntry.getValue());
91 }
92 } else {
93 old.clear();
94 old.putAll(contextMap);
95 }
96 }
97 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.Map;
29
30 import org.apache.log4j.MDCFriend;
31 import org.slf4j.spi.MDCAdapter;
32
33 public class Log4jMDCAdapter implements MDCAdapter {
34
35 static {
36 if (VersionUtil.getJavaMajorVersion() >= 9) {
37 MDCFriend.fixForJava9();
38 }
39 }
40
41 public void clear() {
42 @SuppressWarnings("rawtypes")
43 Map map = org.apache.log4j.MDC.getContext();
44 if (map != null) {
45 map.clear();
46 }
47 }
48
49 public String get(String key) {
50 return (String) org.apache.log4j.MDC.get(key);
51 }
52
53 /**
54 * Put a context value (the <code>val</code> parameter) as identified with
55 * the <code>key</code> parameter into the current thread's context map. The
56 * <code>key</code> parameter cannot be null. Log4j does <em>not</em>
57 * support null for the <code>val</code> parameter.
58 *
59 * <p>
60 * This method delegates all work to log4j's MDC.
61 *
62 * @throws IllegalArgumentException
63 * in case the "key" or <b>"val"</b> parameter is null
64 */
65 public void put(String key, String val) {
66 org.apache.log4j.MDC.put(key, val);
67 }
68
69 public void remove(String key) {
70 org.apache.log4j.MDC.remove(key);
71 }
72
73 @SuppressWarnings({ "rawtypes", "unchecked" })
74 public Map getCopyOfContextMap() {
75 Map old = org.apache.log4j.MDC.getContext();
76 if (old != null) {
77 return new HashMap(old);
78 } else {
79 return null;
80 }
81 }
82
83 @SuppressWarnings({ "rawtypes", "unchecked" })
84 public void setContextMap(Map contextMap) {
85 Map old = org.apache.log4j.MDC.getContext();
86 if (old == null) {
87 Iterator entrySetIterator = contextMap.entrySet().iterator();
88 while (entrySetIterator.hasNext()) {
89 Map.Entry mapEntry = (Map.Entry) entrySetIterator.next();
90 org.apache.log4j.MDC.put((String) mapEntry.getKey(), mapEntry.getValue());
91 }
92 } else {
93 old.clear();
94 old.putAll(contextMap);
95 }
96 }
97 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.apache.log4j.Level;
27 import org.slf4j.ILoggerFactory;
28 import org.slf4j.LoggerFactory;
29 import org.slf4j.helpers.Util;
30 import org.slf4j.spi.LoggerFactoryBinder;
31
32 /**
33 * The binding of {@link LoggerFactory} class with an actual instance of
34 * {@link ILoggerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticLoggerBinder implements LoggerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 *
43 */
44 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
45
46 /**
47 * Return the singleton of this class.
48 *
49 * @return the StaticLoggerBinder singleton
50 */
51 public static final StaticLoggerBinder getSingleton() {
52 return SINGLETON;
53 }
54
55 /**
56 * Declare the version of the SLF4J API this implementation is compiled against.
57 * The value of this field is modified with each major release.
58 */
59 // to avoid constant folding by the compiler, this field must *not* be final
60 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
61
62 private static final String loggerFactoryClassStr = Log4jLoggerFactory.class.getName();
63
64 /**
65 * The ILoggerFactory instance returned by the {@link #getLoggerFactory}
66 * method should always be the same object
67 */
68 private final ILoggerFactory loggerFactory;
69
70 private StaticLoggerBinder() {
71 loggerFactory = new Log4jLoggerFactory();
72 try {
73 @SuppressWarnings("unused")
74 Level level = Level.TRACE;
75 } catch (NoSuchFieldError nsfe) {
76 Util.report("This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version");
77 }
78 }
79
80 public ILoggerFactory getLoggerFactory() {
81 return loggerFactory;
82 }
83
84 public String getLoggerFactoryClassStr() {
85 return loggerFactoryClassStr;
86 }
87 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.apache.log4j.Level;
27 import org.slf4j.ILoggerFactory;
28 import org.slf4j.LoggerFactory;
29 import org.slf4j.helpers.Util;
30 import org.slf4j.spi.LoggerFactoryBinder;
31
32 /**
33 * The binding of {@link LoggerFactory} class with an actual instance of
34 * {@link ILoggerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticLoggerBinder implements LoggerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 *
43 */
44 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
45
46 /**
47 * Return the singleton of this class.
48 *
49 * @return the StaticLoggerBinder singleton
50 */
51 public static final StaticLoggerBinder getSingleton() {
52 return SINGLETON;
53 }
54
55 /**
56 * Declare the version of the SLF4J API this implementation is compiled against.
57 * The value of this field is modified with each major release.
58 */
59 // to avoid constant folding by the compiler, this field must *not* be final
60 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
61
62 private static final String loggerFactoryClassStr = Log4jLoggerFactory.class.getName();
63
64 /**
65 * The ILoggerFactory instance returned by the {@link #getLoggerFactory}
66 * method should always be the same object
67 */
68 private final ILoggerFactory loggerFactory;
69
70 private StaticLoggerBinder() {
71 loggerFactory = new Log4jLoggerFactory();
72 try {
73 @SuppressWarnings("unused")
74 Level level = Level.TRACE;
75 } catch (NoSuchFieldError nsfe) {
76 Util.report("This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version");
77 }
78 }
79
80 public ILoggerFactory getLoggerFactory() {
81 return loggerFactory;
82 }
83
84 public String getLoggerFactoryClassStr() {
85 return loggerFactoryClassStr;
86 }
87 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.spi.MDCAdapter;
27
28 /**
29 * This implementation is bound to {@link Log4jMDCAdapter}.
30 *
31 * @author Ceki G&uuml;lc&uuml;
32 */
33 public class StaticMDCBinder {
34
35 /**
36 * The unique instance of this class.
37 */
38 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
39
40 private StaticMDCBinder() {
41 }
42
43 /**
44 * Return the singleton of this class.
45 *
46 * @return the StaticMDCBinder singleton
47 * @since 1.7.14
48 */
49 public static final StaticMDCBinder getSingleton() {
50 return SINGLETON;
51 }
52
53 /**
54 * Currently this method always returns an instance of
55 * {@link StaticMDCBinder}.
56 */
57 public MDCAdapter getMDCA() {
58 return new Log4jMDCAdapter();
59 }
60
61 public String getMDCAdapterClassStr() {
62 return Log4jMDCAdapter.class.getName();
63 }
64 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.spi.MDCAdapter;
27
28 /**
29 * This implementation is bound to {@link Log4jMDCAdapter}.
30 *
31 * @author Ceki G&uuml;lc&uuml;
32 */
33 public class StaticMDCBinder {
34
35 /**
36 * The unique instance of this class.
37 */
38 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
39
40 private StaticMDCBinder() {
41 }
42
43 /**
44 * Return the singleton of this class.
45 *
46 * @return the StaticMDCBinder singleton
47 * @since 1.7.14
48 */
49 public static final StaticMDCBinder getSingleton() {
50 return SINGLETON;
51 }
52
53 /**
54 * Currently this method always returns an instance of
55 * {@link StaticMDCBinder}.
56 */
57 public MDCAdapter getMDCA() {
58 return new Log4jMDCAdapter();
59 }
60
61 public String getMDCAdapterClassStr() {
62 return Log4jMDCAdapter.class.getName();
63 }
64 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Return the singleton of this class.
52 *
53 * @return the StaticMarkerBinder singleton
54 * @since 1.7.14
55 */
56 public static StaticMarkerBinder getSingleton() {
57 return SINGLETON;
58 }
59
60 /**
61 * Currently this method always returns an instance of
62 * {@link BasicMarkerFactory}.
63 */
64 public IMarkerFactory getMarkerFactory() {
65 return markerFactory;
66 }
67
68 /**
69 * Currently, this method returns the class name of
70 * {@link BasicMarkerFactory}.
71 */
72 public String getMarkerFactoryClassStr() {
73 return BasicMarkerFactory.class.getName();
74 }
75
76 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Return the singleton of this class.
52 *
53 * @return the StaticMarkerBinder singleton
54 * @since 1.7.14
55 */
56 public static StaticMarkerBinder getSingleton() {
57 return SINGLETON;
58 }
59
60 /**
61 * Currently this method always returns an instance of
62 * {@link BasicMarkerFactory}.
63 */
64 public IMarkerFactory getMarkerFactory() {
65 return markerFactory;
66 }
67
68 /**
69 * Currently, this method returns the class name of
70 * {@link BasicMarkerFactory}.
71 */
72 public String getMarkerFactoryClassStr() {
73 return BasicMarkerFactory.class.getName();
74 }
75
76 }
0 package org.slf4j.impl;
1
2 import java.lang.reflect.Method;
3
4 import org.slf4j.helpers.Util;
5
6 public class VersionUtil {
7 static final int MINIMAL_VERSION = 5;
8
9 static public int getJavaMajorVersion() {
10 String javaVersionString = Util.safeGetSystemProperty("java.version");
11 return getJavaMajorVersion(javaVersionString);
12 }
13
14 static int getJavaMajorVersion(String versionString) {
15 if (versionString == null)
16 return MINIMAL_VERSION;
17 if (versionString.startsWith("1.")) {
18 return versionString.charAt(2) - '0';
19 } else {
20 // we running under Java 9 or later
21 try {
22 Method versionMethod = Runtime.class.getMethod("version");
23 Object versionObj = versionMethod.invoke(null);
24 Method majorMethod = versionObj.getClass().getMethod("major");
25 Integer resultInteger = (Integer) majorMethod.invoke(versionObj);
26 return resultInteger.intValue();
27 } catch (Exception e) {
28 return MINIMAL_VERSION;
29 }
30 }
31 }
32 }
0 package org.slf4j.impl;
1
2 import java.lang.reflect.Method;
3
4 import org.slf4j.helpers.Util;
5
6 public class VersionUtil {
7 static final int MINIMAL_VERSION = 5;
8
9 static public int getJavaMajorVersion() {
10 String javaVersionString = Util.safeGetSystemProperty("java.version");
11 return getJavaMajorVersion(javaVersionString);
12 }
13
14 static int getJavaMajorVersion(String versionString) {
15 if (versionString == null)
16 return MINIMAL_VERSION;
17 if (versionString.startsWith("1.")) {
18 return versionString.charAt(2) - '0';
19 } else {
20 // we running under Java 9 or later
21 try {
22 Method versionMethod = Runtime.class.getMethod("version");
23 Object versionObj = versionMethod.invoke(null);
24 Method majorMethod = versionObj.getClass().getMethod("major");
25 Integer resultInteger = (Integer) majorMethod.invoke(versionObj);
26 return resultInteger.intValue();
27 } catch (Exception e) {
28 return MINIMAL_VERSION;
29 }
30 }
31 }
32 }
0 Implementation-Title: slf4j-log4j12
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.log4j12
3 Bundle-Name: slf4j-log4j12
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},
8 org.slf4j.spi;version=${parsedVersion.osgiVersion},
9 org.slf4j.helpers;version=${parsedVersion.osgiVersion},
10 org.slf4j.event;version=${parsedVersion.osgiVersion},
11 org.apache.log4j
0 Implementation-Title: slf4j-log4j12
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.log4j12
3 Bundle-Name: slf4j-log4j12
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},
8 org.slf4j.spi;version=${parsedVersion.osgiVersion},
9 org.slf4j.helpers;version=${parsedVersion.osgiVersion},
10 org.slf4j.event;version=${parsedVersion.osgiVersion},
11 org.apache.log4j
1212 Fragment-Host: slf4j.api
0 package org.apache.log4j;
1
2 import static org.junit.Assert.assertEquals;
3 import static org.junit.Assert.assertNull;
4
5 import java.util.Random;
6
7 import org.junit.Test;
8 import org.slf4j.impl.VersionUtil;
9
10 public class MDCFriendTest {
11
12
13 private static Random random = new Random();
14 int diff = random.nextInt(1024*8);
15
16 @Test
17 public void smoke() {
18 if(VersionUtil.getJavaMajorVersion() < 9)
19 return;
20
21 MDCFriend.fixForJava9();
22 String key = "MDCFriendTest.smoke"+diff;
23 String val = "val"+diff;
24 MDC.put(key, val);
25 assertEquals(val, MDC.get(key));
26 MDC.clear();
27 assertNull(MDC.get(key));
28
29 }
30
31 }
0 package org.apache.log4j;
1
2 import static org.junit.Assert.assertEquals;
3 import static org.junit.Assert.assertNull;
4
5 import java.util.Random;
6
7 import org.junit.Test;
8 import org.slf4j.impl.VersionUtil;
9
10 public class MDCFriendTest {
11
12
13 private static Random random = new Random();
14 int diff = random.nextInt(1024*8);
15
16 @Test
17 public void smoke() {
18 if(VersionUtil.getJavaMajorVersion() < 9)
19 return;
20
21 MDCFriend.fixForJava9();
22 String key = "MDCFriendTest.smoke"+diff;
23 String val = "val"+diff;
24 MDC.put(key, val);
25 assertEquals(val, MDC.get(key));
26 MDC.clear();
27 assertNull(MDC.get(key));
28
29 }
30
31 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.fail;
30
31 import java.util.HashMap;
32 import java.util.Map;
33
34 import org.apache.log4j.spi.LoggingEvent;
35 import org.junit.After;
36 import org.junit.Before;
37 import org.junit.Test;
38
39 /**
40 * Test whether invoking the SLF4J API causes problems or not.
41 *
42 * @author Ceki Gulcu
43 *
44 */
45 public class InvocationTest {
46
47 ListAppender listAppender = new ListAppender();
48 org.apache.log4j.Logger root;
49
50 @Before
51 public void setUp() throws Exception {
52 root = org.apache.log4j.Logger.getRootLogger();
53 root.addAppender(listAppender);
54 }
55
56 @After
57 public void tearDown() throws Exception {
58 root.getLoggerRepository().resetConfiguration();
59 }
60
61 @Test
62 public void test1() {
63 Logger logger = LoggerFactory.getLogger("test1");
64 logger.debug("Hello world.");
65 assertEquals(1, listAppender.list.size());
66 }
67
68 @Test
69 public void test2() {
70 Integer i1 = Integer.valueOf(1);
71 Integer i2 = Integer.valueOf(2);
72 Integer i3 = Integer.valueOf(3);
73 Exception e = new Exception("This is a test exception.");
74 Logger logger = LoggerFactory.getLogger("test2");
75
76 logger.trace("Hello trace.");
77
78 logger.debug("Hello world 1.");
79 logger.debug("Hello world {}", i1);
80 logger.debug("val={} val={}", i1, i2);
81 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
82
83 logger.debug("Hello world 2", e);
84 logger.info("Hello world 2.");
85
86 logger.warn("Hello world 3.");
87 logger.warn("Hello world 3", e);
88
89 logger.error("Hello world 4.");
90 logger.error("Hello world {}", Integer.valueOf(3));
91 logger.error("Hello world 4.", e);
92 assertEquals(11, listAppender.list.size());
93 }
94
95 @Test
96 public void testNull() {
97 Logger logger = LoggerFactory.getLogger("testNull");
98 logger.trace(null);
99 logger.debug(null);
100 logger.info(null);
101 logger.warn(null);
102 logger.error(null);
103
104 Exception e = new Exception("This is a test exception.");
105 logger.debug(null, e);
106 logger.info(null, e);
107 logger.warn(null, e);
108 logger.error(null, e);
109 assertEquals(8, listAppender.list.size());
110 }
111
112 // http://jira.qos.ch/browse/SLF4J-69
113 // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=78
114 @Test
115 public void testNullParameter_BUG78() {
116 Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78");
117 String[] parameters = null;
118 String msg = "hello {}";
119
120 logger.debug(msg, (Object[]) parameters);
121
122 assertEquals(1, listAppender.list.size());
123 LoggingEvent e = (LoggingEvent) listAppender.list.get(0);
124 assertEquals(msg, e.getMessage());
125 }
126
127 @Test
128 public void testMarker() {
129 Logger logger = LoggerFactory.getLogger("testMarker");
130 Marker blue = MarkerFactory.getMarker("BLUE");
131 logger.trace(blue, "hello");
132 logger.debug(blue, "hello");
133 logger.info(blue, "hello");
134 logger.warn(blue, "hello");
135 logger.error(blue, "hello");
136
137 logger.debug(blue, "hello {}", "world");
138 logger.info(blue, "hello {}", "world");
139 logger.warn(blue, "hello {}", "world");
140 logger.error(blue, "hello {}", "world");
141
142 logger.debug(blue, "hello {} and {} ", "world", "universe");
143 logger.info(blue, "hello {} and {} ", "world", "universe");
144 logger.warn(blue, "hello {} and {} ", "world", "universe");
145 logger.error(blue, "hello {} and {} ", "world", "universe");
146 assertEquals(12, listAppender.list.size());
147 }
148
149 @Test
150 public void testMDC() {
151 MDC.put("k", "v");
152 assertNotNull(MDC.get("k"));
153 assertEquals("v", MDC.get("k"));
154
155 MDC.remove("k");
156 assertNull(MDC.get("k"));
157
158 MDC.put("k1", "v1");
159 assertEquals("v1", MDC.get("k1"));
160 MDC.clear();
161 assertNull(MDC.get("k1"));
162
163 try {
164 MDC.put(null, "x");
165 fail("null keys are invalid");
166 } catch (IllegalArgumentException e) {
167 }
168 }
169
170 @Test
171 public void testMDCContextMapValues() {
172 Map<String, String> map = new HashMap<String, String>();
173 map.put("ka", "va");
174 map.put("kb", "vb");
175
176 MDC.put("k", "v");
177 assertEquals("v", MDC.get("k"));
178 MDC.setContextMap(map);
179 assertNull(MDC.get("k"));
180 assertEquals("va", MDC.get("ka"));
181 assertEquals("vb", MDC.get("kb"));
182 }
183
184 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.fail;
30
31 import java.util.HashMap;
32 import java.util.Map;
33
34 import org.apache.log4j.spi.LoggingEvent;
35 import org.junit.After;
36 import org.junit.Before;
37 import org.junit.Test;
38
39 /**
40 * Test whether invoking the SLF4J API causes problems or not.
41 *
42 * @author Ceki Gulcu
43 *
44 */
45 public class InvocationTest {
46
47 ListAppender listAppender = new ListAppender();
48 org.apache.log4j.Logger root;
49
50 @Before
51 public void setUp() throws Exception {
52 root = org.apache.log4j.Logger.getRootLogger();
53 root.addAppender(listAppender);
54 }
55
56 @After
57 public void tearDown() throws Exception {
58 root.getLoggerRepository().resetConfiguration();
59 }
60
61 @Test
62 public void test1() {
63 Logger logger = LoggerFactory.getLogger("test1");
64 logger.debug("Hello world.");
65 assertEquals(1, listAppender.list.size());
66 }
67
68 @Test
69 public void test2() {
70 Integer i1 = Integer.valueOf(1);
71 Integer i2 = Integer.valueOf(2);
72 Integer i3 = Integer.valueOf(3);
73 Exception e = new Exception("This is a test exception.");
74 Logger logger = LoggerFactory.getLogger("test2");
75
76 logger.trace("Hello trace.");
77
78 logger.debug("Hello world 1.");
79 logger.debug("Hello world {}", i1);
80 logger.debug("val={} val={}", i1, i2);
81 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
82
83 logger.debug("Hello world 2", e);
84 logger.info("Hello world 2.");
85
86 logger.warn("Hello world 3.");
87 logger.warn("Hello world 3", e);
88
89 logger.error("Hello world 4.");
90 logger.error("Hello world {}", Integer.valueOf(3));
91 logger.error("Hello world 4.", e);
92 assertEquals(11, listAppender.list.size());
93 }
94
95 @Test
96 public void testNull() {
97 Logger logger = LoggerFactory.getLogger("testNull");
98 logger.trace(null);
99 logger.debug(null);
100 logger.info(null);
101 logger.warn(null);
102 logger.error(null);
103
104 Exception e = new Exception("This is a test exception.");
105 logger.debug(null, e);
106 logger.info(null, e);
107 logger.warn(null, e);
108 logger.error(null, e);
109 assertEquals(8, listAppender.list.size());
110 }
111
112 // http://jira.qos.ch/browse/SLF4J-69
113 // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=78
114 @Test
115 public void testNullParameter_BUG78() {
116 Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78");
117 String[] parameters = null;
118 String msg = "hello {}";
119
120 logger.debug(msg, (Object[]) parameters);
121
122 assertEquals(1, listAppender.list.size());
123 LoggingEvent e = (LoggingEvent) listAppender.list.get(0);
124 assertEquals(msg, e.getMessage());
125 }
126
127 @Test
128 public void testMarker() {
129 Logger logger = LoggerFactory.getLogger("testMarker");
130 Marker blue = MarkerFactory.getMarker("BLUE");
131 logger.trace(blue, "hello");
132 logger.debug(blue, "hello");
133 logger.info(blue, "hello");
134 logger.warn(blue, "hello");
135 logger.error(blue, "hello");
136
137 logger.debug(blue, "hello {}", "world");
138 logger.info(blue, "hello {}", "world");
139 logger.warn(blue, "hello {}", "world");
140 logger.error(blue, "hello {}", "world");
141
142 logger.debug(blue, "hello {} and {} ", "world", "universe");
143 logger.info(blue, "hello {} and {} ", "world", "universe");
144 logger.warn(blue, "hello {} and {} ", "world", "universe");
145 logger.error(blue, "hello {} and {} ", "world", "universe");
146 assertEquals(12, listAppender.list.size());
147 }
148
149 @Test
150 public void testMDC() {
151 MDC.put("k", "v");
152 assertNotNull(MDC.get("k"));
153 assertEquals("v", MDC.get("k"));
154
155 MDC.remove("k");
156 assertNull(MDC.get("k"));
157
158 MDC.put("k1", "v1");
159 assertEquals("v1", MDC.get("k1"));
160 MDC.clear();
161 assertNull(MDC.get("k1"));
162
163 try {
164 MDC.put(null, "x");
165 fail("null keys are invalid");
166 } catch (IllegalArgumentException e) {
167 }
168 }
169
170 @Test
171 public void testMDCContextMapValues() {
172 Map<String, String> map = new HashMap<String, String>();
173 map.put("ka", "va");
174 map.put("kb", "vb");
175
176 MDC.put("k", "v");
177 assertEquals("v", MDC.get("k"));
178 MDC.setContextMap(map);
179 assertNull(MDC.get("k"));
180 assertEquals("va", MDC.get("ka"));
181 assertEquals("vb", MDC.get("kb"));
182 }
183
184 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.apache.log4j.AppenderSkeleton;
30 import org.apache.log4j.spi.LoggingEvent;
31
32 public class ListAppender extends AppenderSkeleton {
33
34 public List<LoggingEvent> list = new ArrayList<LoggingEvent>();
35
36 public boolean extractLocationInfo = false;
37
38 protected void append(LoggingEvent event) {
39 list.add(event);
40 if (extractLocationInfo) {
41 event.getLocationInformation();
42 }
43 }
44
45 public void close() {
46 }
47
48 public boolean requiresLayout() {
49 return false;
50 }
51
52 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.apache.log4j.AppenderSkeleton;
30 import org.apache.log4j.spi.LoggingEvent;
31
32 public class ListAppender extends AppenderSkeleton {
33
34 public List<LoggingEvent> list = new ArrayList<LoggingEvent>();
35
36 public boolean extractLocationInfo = false;
37
38 protected void append(LoggingEvent event) {
39 list.add(event);
40 if (extractLocationInfo) {
41 event.getLocationInformation();
42 }
43 }
44
45 public void close() {
46 }
47
48 public boolean requiresLayout() {
49 return false;
50 }
51
52 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.List;
27
28 import org.apache.log4j.LogManager;
29 import org.apache.log4j.spi.LoggingEvent;
30 import org.junit.After;
31 import org.junit.Before;
32 import static org.junit.Assert.assertNotNull;
33
34 import org.slf4j.helpers.MultithreadedInitializationTest;
35
36 public class Log4j12MultithreadedInitializationTest extends MultithreadedInitializationTest {
37 static int NUM_LINES_BY_RECURSIVE_APPENDER = 3;
38
39 // value of LogManager.DEFAULT_CONFIGURATION_KEY;
40 static String CONFIG_FILE_KEY = "log4j.configuration";
41 final String loggerName = this.getClass().getName();
42
43 @Before
44 public void setup() {
45 System.setProperty(CONFIG_FILE_KEY, "recursiveInitWithActivationDelay.properties");
46 System.out.println("THREAD_COUNT=" + THREAD_COUNT);
47 }
48
49 @After
50 public void tearDown() throws Exception {
51 System.clearProperty(CONFIG_FILE_KEY);
52 }
53
54 protected long getRecordedEventCount() {
55 List<LoggingEvent> eventList = getRecordedEvents();
56 assertNotNull(eventList);
57 return eventList.size();
58 }
59
60 protected int extraLogEvents() {
61 return NUM_LINES_BY_RECURSIVE_APPENDER;
62 }
63
64 private List<LoggingEvent> getRecordedEvents() {
65 org.apache.log4j.Logger root = LogManager.getRootLogger();
66
67 RecursiveAppender ra = (RecursiveAppender) root.getAppender("RECURSIVE");
68 assertNotNull(ra);
69 return ra.events;
70 }
71
72 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.List;
27
28 import org.apache.log4j.LogManager;
29 import org.apache.log4j.spi.LoggingEvent;
30 import org.junit.After;
31 import org.junit.Before;
32 import static org.junit.Assert.assertNotNull;
33
34 import org.slf4j.helpers.MultithreadedInitializationTest;
35
36 public class Log4j12MultithreadedInitializationTest extends MultithreadedInitializationTest {
37 static int NUM_LINES_BY_RECURSIVE_APPENDER = 3;
38
39 // value of LogManager.DEFAULT_CONFIGURATION_KEY;
40 static String CONFIG_FILE_KEY = "log4j.configuration";
41 final String loggerName = this.getClass().getName();
42
43 @Before
44 public void setup() {
45 System.setProperty(CONFIG_FILE_KEY, "recursiveInitWithActivationDelay.properties");
46 System.out.println("THREAD_COUNT=" + THREAD_COUNT);
47 }
48
49 @After
50 public void tearDown() throws Exception {
51 System.clearProperty(CONFIG_FILE_KEY);
52 }
53
54 protected long getRecordedEventCount() {
55 List<LoggingEvent> eventList = getRecordedEvents();
56 assertNotNull(eventList);
57 return eventList.size();
58 }
59
60 protected int extraLogEvents() {
61 return NUM_LINES_BY_RECURSIVE_APPENDER;
62 }
63
64 private List<LoggingEvent> getRecordedEvents() {
65 org.apache.log4j.Logger root = LogManager.getRootLogger();
66
67 RecursiveAppender ra = (RecursiveAppender) root.getAppender("RECURSIVE");
68 assertNotNull(ra);
69 return ra.events;
70 }
71
72 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Random;
29
30 import org.apache.log4j.AppenderSkeleton;
31 import org.apache.log4j.spi.LoggingEvent;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 public class RecursiveAppender extends AppenderSkeleton {
36
37 int diff = new Random().nextInt();
38 int activationDelay = 0;
39 String loggerName = "org.slf4j.impl.RecursiveAppender" + diff;
40
41 List<LoggingEvent> events = new ArrayList<LoggingEvent>();
42
43 public RecursiveAppender() {
44 System.out.println("entering RecursiveAppender constructor");
45 Logger logger = LoggerFactory.getLogger(loggerName);
46 logger.info("Calling a logger in the constructor");
47 System.out.println("exiting RecursiveAppender constructor");
48 }
49
50 protected void append(LoggingEvent e) {
51 events.add(e);
52 }
53
54 public void close() {
55 }
56
57 public boolean requiresLayout() {
58 return false;
59 }
60
61 @Override
62 public void activateOptions() {
63 System.out.println("entering RecursiveAppender.activateOptions");
64 if (activationDelay > 0) {
65 Logger logger = LoggerFactory.getLogger(loggerName);
66 logger.info("About to wait {} millis", activationDelay);
67 try {
68 Thread.sleep(activationDelay);
69 } catch (InterruptedException e) {
70 e.printStackTrace();
71 }
72 logger.info("Done waiting {} millis", activationDelay);
73 }
74 super.activateOptions();
75
76 System.out.println("exiting RecursiveAppender.activateOptions");
77 }
78
79 public int getActivationDelay() {
80 return activationDelay;
81 }
82
83 public void setActivationDelay(int activationDelay) {
84 this.activationDelay = activationDelay;
85 }
86
87 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Random;
29
30 import org.apache.log4j.AppenderSkeleton;
31 import org.apache.log4j.spi.LoggingEvent;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 public class RecursiveAppender extends AppenderSkeleton {
36
37 int diff = new Random().nextInt();
38 int activationDelay = 0;
39 String loggerName = "org.slf4j.impl.RecursiveAppender" + diff;
40
41 List<LoggingEvent> events = new ArrayList<LoggingEvent>();
42
43 public RecursiveAppender() {
44 System.out.println("entering RecursiveAppender constructor");
45 Logger logger = LoggerFactory.getLogger(loggerName);
46 logger.info("Calling a logger in the constructor");
47 System.out.println("exiting RecursiveAppender constructor");
48 }
49
50 protected void append(LoggingEvent e) {
51 events.add(e);
52 }
53
54 public void close() {
55 }
56
57 public boolean requiresLayout() {
58 return false;
59 }
60
61 @Override
62 public void activateOptions() {
63 System.out.println("entering RecursiveAppender.activateOptions");
64 if (activationDelay > 0) {
65 Logger logger = LoggerFactory.getLogger(loggerName);
66 logger.info("About to wait {} millis", activationDelay);
67 try {
68 Thread.sleep(activationDelay);
69 } catch (InterruptedException e) {
70 e.printStackTrace();
71 }
72 logger.info("Done waiting {} millis", activationDelay);
73 }
74 super.activateOptions();
75
76 System.out.println("exiting RecursiveAppender.activateOptions");
77 }
78
79 public int getActivationDelay() {
80 return activationDelay;
81 }
82
83 public void setActivationDelay(int activationDelay) {
84 this.activationDelay = activationDelay;
85 }
86
87 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.Random;
27
28 import org.junit.After;
29 import org.junit.Test;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 public class RecursiveInitializationTest {
34
35 // value of LogManager.DEFAULT_CONFIGURATION_KEY;
36 static String CONFIG_FILE_KEY = "log4j.configuration";
37
38 int diff = new Random().nextInt(10000);
39 String loggerName = "org.slf4j.impl.RecursiveInitializationTest";
40
41 @After
42 public void tearDown() throws Exception {
43 System.clearProperty(CONFIG_FILE_KEY);
44 }
45
46 @Test
47 public void loggingDuringInitialization() {
48 System.setProperty(CONFIG_FILE_KEY, "recursiveInit.properties");
49 Logger logger = LoggerFactory.getLogger(loggerName + ".loggingDuringInitialization-" + diff);
50 logger.info("hello");
51 }
52
53 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.Random;
27
28 import org.junit.After;
29 import org.junit.Test;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 public class RecursiveInitializationTest {
34
35 // value of LogManager.DEFAULT_CONFIGURATION_KEY;
36 static String CONFIG_FILE_KEY = "log4j.configuration";
37
38 int diff = new Random().nextInt(10000);
39 String loggerName = "org.slf4j.impl.RecursiveInitializationTest";
40
41 @After
42 public void tearDown() throws Exception {
43 System.clearProperty(CONFIG_FILE_KEY);
44 }
45
46 @Test
47 public void loggingDuringInitialization() {
48 System.setProperty(CONFIG_FILE_KEY, "recursiveInit.properties");
49 Logger logger = LoggerFactory.getLogger(loggerName + ".loggingDuringInitialization-" + diff);
50 logger.info("hello");
51 }
52
53 }
0 package org.slf4j.impl;
1
2 import static org.junit.Assert.*;
3
4 import org.junit.Ignore;
5 import org.junit.Test;
6
7 public class UtilVersionTest {
8
9 @Test
10 public void test() {
11 System.out.println(System.getProperty("java.version"));
12 assertEquals(6, VersionUtil.getJavaMajorVersion("1.6"));
13 assertEquals(7, VersionUtil.getJavaMajorVersion("1.7.0_21-b11"));
14 assertEquals(8, VersionUtil.getJavaMajorVersion("1.8.0_25"));
15 }
16
17 @Ignore
18 @Test // requires Java 9 to pass
19 public void testJava9() {
20 assertEquals(9, VersionUtil.getJavaMajorVersion("9ea"));
21 }
22
23 }
0 package org.slf4j.impl;
1
2 import static org.junit.Assert.*;
3
4 import org.junit.Ignore;
5 import org.junit.Test;
6
7 public class UtilVersionTest {
8
9 @Test
10 public void test() {
11 System.out.println(System.getProperty("java.version"));
12 assertEquals(6, VersionUtil.getJavaMajorVersion("1.6"));
13 assertEquals(7, VersionUtil.getJavaMajorVersion("1.7.0_21-b11"));
14 assertEquals(8, VersionUtil.getJavaMajorVersion("1.8.0_25"));
15 }
16
17 @Ignore
18 @Test // requires Java 9 to pass
19 public void testJava9() {
20 assertEquals(9, VersionUtil.getJavaMajorVersion("9ea"));
21 }
22
23 }
0 log4j.debug=true
1 log4j.rootLogger=DEBUG, RECURSIVE
2
3 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
4 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
5 log4j.appender.CONSOLE.layout.ConversionPattern=%d [%t] %c - %m%n
6
0 log4j.debug=true
1 log4j.rootLogger=DEBUG, RECURSIVE
2
3 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
4 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
5 log4j.appender.CONSOLE.layout.ConversionPattern=%d [%t] %c - %m%n
6
77 log4j.appender.RECURSIVE=org.slf4j.impl.RecursiveAppender
0 log4j.debug=true
1 log4j.rootLogger=DEBUG, CONSOLE, RECURSIVE
2
3 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
4 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
5 log4j.appender.CONSOLE.layout.ConversionPattern=CON %d [%t] %c - %m%n
6
7 log4j.appender.RECURSIVE=org.slf4j.impl.RecursiveAppender
0 log4j.debug=true
1 log4j.rootLogger=DEBUG, CONSOLE, RECURSIVE
2
3 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
4 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
5 log4j.appender.CONSOLE.layout.ConversionPattern=CON %d [%t] %c - %m%n
6
7 log4j.appender.RECURSIVE=org.slf4j.impl.RecursiveAppender
88 log4j.appender.RECURSIVE.activationDelay=10
0
1 The slf4j-migrator aims to
2
3 General limitations
4 ===================
5
6 - the FATAL level is not supported.
7
8 This is limitation is not deemed serious because there are usually
9 very few log statements bearing the FATAL level.
10
11
12 - if a method declares multiple loggers on the same line, the conversion will not be complete. Example:
13
14
15 public void someMethod(Log l1, Log l2) {
16 ...
17 }
18
19 will be converted as
20
21 public void someMethod(Log l1, Logger l2) {
22 ...
23 }
24
25
26 When migrating from log4j
27 =========================
28
29 - Since NDC is not supported by SLF4J, the migrator cannot properly handle
30 NDC statements.
31
32 - Calls to PropertyConfigurator or DomConfigurator cannot be migrated since
33 SLF4J the equivalents.
0 /**
1 *This is not a class, just a sample of some jcl source code to convert
2 */
3 import org.apache.commons.logging.LogFactory;
4 import org.apache.commons.logging.Log;
5
6
7 Log l = LogFactory.getLog(MyClass.class);
8 Log mylog=LogFactory.getLog(MyClass.class);
9 Log mylog1 = LogFactory.getLog(MyClass.class);
10 Log mylog2 = LogFactory.getLog(MyClass.class);
11
12 Log log3=LogFactory.getFactory().getInstance(MyClass.class);
13 Log mylog4 = LogFactory.getFactory().getInstance(MyClass.class);
14 Log mylog5 = LogFactory.getLog(MyClass.class);
15
16 Log myLog6;
17
18 log7=LogFactory.getFactory().getInstance(MyClass.class);
19 log8 =LogFactory.getFactory().getInstance(MyClass.class);
20 myLog9 = LogFactory.getLog(MyClass.class);
21
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>slf4j-migrator</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J Migrator</name>
16 <description>SLF4J Migrator</description>
17
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>slf4j-migrator</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J Migrator</name>
16 <description>SLF4J Migrator</description>
17
1818 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 public class Constant {
27
28 public final static int JCL_TO_SLF4J = 0;
29 public final static int LOG4J_TO_SLF4J = 1;
30 public final static int JUL_TO_SLF4J = 2;
31 public final static int NOP_TO_SLF4J = 3;
32
33 public final static int NB_FILES_MAX = 1;
34
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 public class Constant {
27
28 public final static int JCL_TO_SLF4J = 0;
29 public final static int LOG4J_TO_SLF4J = 1;
30 public final static int JUL_TO_SLF4J = 2;
31 public final static int NOP_TO_SLF4J = 3;
32
33 public final static int NB_FILES_MAX = 1;
34
3535 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 public class ConversionException extends Exception {
27
28 /**
29 *
30 */
31 private static final long serialVersionUID = 498961799888576668L;
32
33 private String detail;
34
35 public static final String NOT_IMPLEMENTED = "Conversion mode not implemented yet";
36 public static final String INVALID_DIRECTORY = "Invalid source directory";
37 public static final String FILE_COPY = "Error during file copy";
38
39 public ConversionException(String message) {
40 super(message);
41 }
42
43 public ConversionException(String message, String detail) {
44 super(message);
45 this.detail = detail;
46 }
47
48 public String getDetail() {
49 return detail;
50 }
51
52 public void setDetail(String detail) {
53 this.detail = detail;
54 }
55
56 public void print() {
57 if (getMessage() != null) {
58 System.out.println(getMessage());
59 }
60 }
61
62 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 public class ConversionException extends Exception {
27
28 /**
29 *
30 */
31 private static final long serialVersionUID = 498961799888576668L;
32
33 private String detail;
34
35 public static final String NOT_IMPLEMENTED = "Conversion mode not implemented yet";
36 public static final String INVALID_DIRECTORY = "Invalid source directory";
37 public static final String FILE_COPY = "Error during file copy";
38
39 public ConversionException(String message) {
40 super(message);
41 }
42
43 public ConversionException(String message, String detail) {
44 super(message);
45 this.detail = detail;
46 }
47
48 public String getDetail() {
49 return detail;
50 }
51
52 public void setDetail(String detail) {
53 this.detail = detail;
54 }
55
56 public void print() {
57 if (getMessage() != null) {
58 System.out.println(getMessage());
59 }
60 }
61
62 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27 import java.util.ArrayList;
28 import java.util.List;
29
30 import org.slf4j.migrator.internal.ProgressListener;
31
32 public class FileSelector {
33
34 private List<File> javaFileList = new ArrayList<File>();
35
36 ProgressListener pl;
37
38 FileSelector(ProgressListener pl) {
39 this.pl = pl;
40 }
41
42 public List<File> selectJavaFilesInFolder(File folder) {
43 if (folder.isDirectory()) {
44 selectFiles(folder);
45 return javaFileList;
46 } else {
47 throw new IllegalArgumentException("[" + folder + "] is not a directory");
48 }
49 }
50
51 private void selectFiles(File file) {
52 if (file.isDirectory()) {
53 pl.onDirectory(file);
54 File[] files = file.listFiles();
55 if (files != null) {
56 for (int i = 0; i < files.length; i++) {
57 selectFiles(files[i]);
58 }
59 }
60 } else {
61 if (file.getName().endsWith(".java")) {
62 pl.onFileAddition(file);
63 javaFileList.add(file);
64 }
65
66 }
67 }
68 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27 import java.util.ArrayList;
28 import java.util.List;
29
30 import org.slf4j.migrator.internal.ProgressListener;
31
32 public class FileSelector {
33
34 private List<File> javaFileList = new ArrayList<File>();
35
36 ProgressListener pl;
37
38 FileSelector(ProgressListener pl) {
39 this.pl = pl;
40 }
41
42 public List<File> selectJavaFilesInFolder(File folder) {
43 if (folder.isDirectory()) {
44 selectFiles(folder);
45 return javaFileList;
46 } else {
47 throw new IllegalArgumentException("[" + folder + "] is not a directory");
48 }
49 }
50
51 private void selectFiles(File file) {
52 if (file.isDirectory()) {
53 pl.onDirectory(file);
54 File[] files = file.listFiles();
55 if (files != null) {
56 for (int i = 0; i < files.length; i++) {
57 selectFiles(files[i]);
58 }
59 }
60 } else {
61 if (file.getName().endsWith(".java")) {
62 pl.onFileAddition(file);
63 javaFileList.add(file);
64 }
65
66 }
67 }
68 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.BufferedReader;
27 import java.io.ByteArrayInputStream;
28 import java.io.ByteArrayOutputStream;
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.FileOutputStream;
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34 import java.io.OutputStream;
35 import java.io.Reader;
36
37 import org.slf4j.migrator.internal.ProgressListener;
38 import org.slf4j.migrator.line.LineConverter;
39 import org.slf4j.migrator.line.RuleSet;
40
41 public class InplaceFileConverter {
42
43 final static int BUFFER_LEN = 8 * 1024;
44 final LineConverter lineConverter;
45 final String lineTerminator;
46 final ProgressListener pl;
47
48 InplaceFileConverter(RuleSet ruleSet, ProgressListener pl) {
49 this.lineConverter = new LineConverter(ruleSet);
50 lineTerminator = System.getProperty("line.separator");
51 this.pl = pl;
52 }
53
54 private byte[] readIntoByteArray(File file) throws IOException {
55 FileInputStream fis = new FileInputStream(file);
56 ByteArrayOutputStream baos = new ByteArrayOutputStream();
57 int n = 0;
58 byte[] buffer = new byte[BUFFER_LEN];
59 while ((n = fis.read(buffer)) != -1) {
60 // System.out.println("ba="+new String(buffer, "UTF-8"));
61 baos.write(buffer, 0, n);
62 }
63 fis.close();
64 return baos.toByteArray();
65 }
66
67 void convert(File file) throws IOException {
68 byte[] originalBytes = readIntoByteArray(file);
69 byte[] convertedBytes = convertIntoTempByteArray(originalBytes);
70 if (lineConverter.atLeastOneMatchOccured()) {
71 // System.out.println("Converting ["+file+"]");
72 writeConvertedBytesIntoFile(file, convertedBytes);
73 pl.onInplaceConversion(file);
74 } else {
75 // System.out.println("Not touching ["+file+"]");
76 }
77 }
78
79 private void writeConvertedBytesIntoFile(File file, byte[] convertedBytes) throws IOException {
80 FileOutputStream fos = new FileOutputStream(file);
81 fos.write(convertedBytes);
82 fos.flush();
83 fos.close();
84 }
85
86 private byte[] convertIntoTempByteArray(byte[] input) throws IOException {
87 ByteArrayInputStream bais = new ByteArrayInputStream(input);
88 Reader reader = new InputStreamReader(bais);
89 BufferedReader breader = new BufferedReader(reader);
90 ByteArrayOutputStream baos = new ByteArrayOutputStream();
91 while (true) {
92 String line = breader.readLine();
93 if (line != null) {
94 String[] replacement = lineConverter.getReplacement(line);
95 writeReplacement(baos, replacement);
96 } else {
97 break;
98 }
99 }
100 return baos.toByteArray();
101 }
102
103 private void writeReplacement(OutputStream os, String[] replacement) throws IOException {
104 for (int i = 0; i < replacement.length; i++) {
105 os.write(replacement[i].getBytes());
106 os.write(lineTerminator.getBytes());
107 }
108 }
109 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.BufferedReader;
27 import java.io.ByteArrayInputStream;
28 import java.io.ByteArrayOutputStream;
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.FileOutputStream;
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34 import java.io.OutputStream;
35 import java.io.Reader;
36
37 import org.slf4j.migrator.internal.ProgressListener;
38 import org.slf4j.migrator.line.LineConverter;
39 import org.slf4j.migrator.line.RuleSet;
40
41 public class InplaceFileConverter {
42
43 final static int BUFFER_LEN = 8 * 1024;
44 final LineConverter lineConverter;
45 final String lineTerminator;
46 final ProgressListener pl;
47
48 InplaceFileConverter(RuleSet ruleSet, ProgressListener pl) {
49 this.lineConverter = new LineConverter(ruleSet);
50 lineTerminator = System.getProperty("line.separator");
51 this.pl = pl;
52 }
53
54 private byte[] readIntoByteArray(File file) throws IOException {
55 FileInputStream fis = new FileInputStream(file);
56 ByteArrayOutputStream baos = new ByteArrayOutputStream();
57 int n = 0;
58 byte[] buffer = new byte[BUFFER_LEN];
59 while ((n = fis.read(buffer)) != -1) {
60 // System.out.println("ba="+new String(buffer, "UTF-8"));
61 baos.write(buffer, 0, n);
62 }
63 fis.close();
64 return baos.toByteArray();
65 }
66
67 void convert(File file) throws IOException {
68 byte[] originalBytes = readIntoByteArray(file);
69 byte[] convertedBytes = convertIntoTempByteArray(originalBytes);
70 if (lineConverter.atLeastOneMatchOccured()) {
71 // System.out.println("Converting ["+file+"]");
72 writeConvertedBytesIntoFile(file, convertedBytes);
73 pl.onInplaceConversion(file);
74 } else {
75 // System.out.println("Not touching ["+file+"]");
76 }
77 }
78
79 private void writeConvertedBytesIntoFile(File file, byte[] convertedBytes) throws IOException {
80 FileOutputStream fos = new FileOutputStream(file);
81 fos.write(convertedBytes);
82 fos.flush();
83 fos.close();
84 }
85
86 private byte[] convertIntoTempByteArray(byte[] input) throws IOException {
87 ByteArrayInputStream bais = new ByteArrayInputStream(input);
88 Reader reader = new InputStreamReader(bais);
89 BufferedReader breader = new BufferedReader(reader);
90 ByteArrayOutputStream baos = new ByteArrayOutputStream();
91 while (true) {
92 String line = breader.readLine();
93 if (line != null) {
94 String[] replacement = lineConverter.getReplacement(line);
95 writeReplacement(baos, replacement);
96 } else {
97 break;
98 }
99 }
100 return baos.toByteArray();
101 }
102
103 private void writeReplacement(OutputStream os, String[] replacement) throws IOException {
104 for (int i = 0; i < replacement.length; i++) {
105 os.write(replacement[i].getBytes());
106 os.write(lineTerminator.getBytes());
107 }
108 }
109 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j.migrator;
26
27 import javax.swing.SwingUtilities;
28
29 import org.slf4j.migrator.internal.MigratorFrame;
30
31 /**
32 * Main entry point to the migrator.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class Main {
37
38 public static void main(String[] args) {
39 System.out.println("Starting SLF4J Migrator");
40 SwingUtilities.invokeLater(new Runnable() {
41 public void run() {
42 MigratorFrame inst = new MigratorFrame();
43 inst.setLocationRelativeTo(null);
44 inst.setVisible(true);
45 }
46 });
47 }
48
49 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j.migrator;
26
27 import javax.swing.SwingUtilities;
28
29 import org.slf4j.migrator.internal.MigratorFrame;
30
31 /**
32 * Main entry point to the migrator.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class Main {
37
38 public static void main(String[] args) {
39 System.out.println("Starting SLF4J Migrator");
40 SwingUtilities.invokeLater(new Runnable() {
41 public void run() {
42 MigratorFrame inst = new MigratorFrame();
43 inst.setLocationRelativeTo(null);
44 inst.setVisible(true);
45 }
46 });
47 }
48
49 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.Iterator;
30 import java.util.List;
31
32 import javax.swing.SwingUtilities;
33
34 import org.slf4j.migrator.internal.MigratorFrame;
35 import org.slf4j.migrator.internal.ProgressListener;
36 import org.slf4j.migrator.line.RuleSet;
37
38 public class ProjectConverter {
39
40 private RuleSet ruleSet;
41 private List<ConversionException> exception;
42
43 ProgressListener progressListener;
44
45 public static void main(String[] args) throws IOException {
46 SwingUtilities.invokeLater(new Runnable() {
47 public void run() {
48 MigratorFrame inst = new MigratorFrame();
49 inst.setLocationRelativeTo(null);
50 inst.setVisible(true);
51 }
52 });
53 }
54
55 /**
56 * Ask for concrete matcher implementation depending on the conversion mode
57 * Ask for user confirmation to convert the selected source directory if valid
58 * Ask for user confirmation in case of number of files to convert > 1000
59 *
60 * @param conversionType
61 * @param progressListener
62 */
63 public ProjectConverter(int conversionType, ProgressListener progressListener) {
64 this.progressListener = progressListener;
65 ruleSet = RuleSetFactory.getMatcherImpl(conversionType);
66 if (ruleSet == null) {
67 addException(new ConversionException(ConversionException.NOT_IMPLEMENTED));
68 }
69 }
70
71 public void convertProject(File folder) {
72 FileSelector fs = new FileSelector(progressListener);
73 List<File> fileList = fs.selectJavaFilesInFolder(folder);
74 scanFileList(fileList);
75 progressListener.onDone();
76 }
77
78 /**
79 * Convert a list of files
80 *
81 * @param lstFiles
82 */
83 private void scanFileList(List<File> lstFiles) {
84 progressListener.onFileScanBegin();
85 Iterator<File> itFile = lstFiles.iterator();
86 while (itFile.hasNext()) {
87 File currentFile = itFile.next();
88 progressListener.onFileScan(currentFile);
89 scanFile(currentFile);
90 }
91 }
92
93 /**
94 * Convert the specified file Read each line and ask matcher implementation
95 * for conversion Rewrite the line returned by matcher
96 *
97 * @param file
98 */
99 private void scanFile(File file) {
100 try {
101 InplaceFileConverter fc = new InplaceFileConverter(ruleSet, progressListener);
102 fc.convert(file);
103 } catch (IOException exc) {
104 addException(new ConversionException(exc.toString()));
105 }
106 }
107
108 public void addException(ConversionException exc) {
109 if (exception == null) {
110 exception = new ArrayList<ConversionException>();
111 }
112 exception.add(exc);
113 }
114
115 public void printException() {
116 if (exception != null) {
117 Iterator<ConversionException> iterator = exception.iterator();
118 while (iterator.hasNext()) {
119 ConversionException exc = (ConversionException) iterator.next();
120 exc.print();
121 }
122 exception = null;
123 }
124 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.Iterator;
30 import java.util.List;
31
32 import javax.swing.SwingUtilities;
33
34 import org.slf4j.migrator.internal.MigratorFrame;
35 import org.slf4j.migrator.internal.ProgressListener;
36 import org.slf4j.migrator.line.RuleSet;
37
38 public class ProjectConverter {
39
40 private RuleSet ruleSet;
41 private List<ConversionException> exception;
42
43 ProgressListener progressListener;
44
45 public static void main(String[] args) throws IOException {
46 SwingUtilities.invokeLater(new Runnable() {
47 public void run() {
48 MigratorFrame inst = new MigratorFrame();
49 inst.setLocationRelativeTo(null);
50 inst.setVisible(true);
51 }
52 });
53 }
54
55 /**
56 * Ask for concrete matcher implementation depending on the conversion mode
57 * Ask for user confirmation to convert the selected source directory if valid
58 * Ask for user confirmation in case of number of files to convert > 1000
59 *
60 * @param conversionType
61 * @param progressListener
62 */
63 public ProjectConverter(int conversionType, ProgressListener progressListener) {
64 this.progressListener = progressListener;
65 ruleSet = RuleSetFactory.getMatcherImpl(conversionType);
66 if (ruleSet == null) {
67 addException(new ConversionException(ConversionException.NOT_IMPLEMENTED));
68 }
69 }
70
71 public void convertProject(File folder) {
72 FileSelector fs = new FileSelector(progressListener);
73 List<File> fileList = fs.selectJavaFilesInFolder(folder);
74 scanFileList(fileList);
75 progressListener.onDone();
76 }
77
78 /**
79 * Convert a list of files
80 *
81 * @param lstFiles
82 */
83 private void scanFileList(List<File> lstFiles) {
84 progressListener.onFileScanBegin();
85 Iterator<File> itFile = lstFiles.iterator();
86 while (itFile.hasNext()) {
87 File currentFile = itFile.next();
88 progressListener.onFileScan(currentFile);
89 scanFile(currentFile);
90 }
91 }
92
93 /**
94 * Convert the specified file Read each line and ask matcher implementation
95 * for conversion Rewrite the line returned by matcher
96 *
97 * @param file
98 */
99 private void scanFile(File file) {
100 try {
101 InplaceFileConverter fc = new InplaceFileConverter(ruleSet, progressListener);
102 fc.convert(file);
103 } catch (IOException exc) {
104 addException(new ConversionException(exc.toString()));
105 }
106 }
107
108 public void addException(ConversionException exc) {
109 if (exception == null) {
110 exception = new ArrayList<ConversionException>();
111 }
112 exception.add(exc);
113 }
114
115 public void printException() {
116 if (exception != null) {
117 Iterator<ConversionException> iterator = exception.iterator();
118 while (iterator.hasNext()) {
119 ConversionException exc = (ConversionException) iterator.next();
120 exc.print();
121 }
122 exception = null;
123 }
124 }
125125 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import org.slf4j.migrator.line.EmptyRuleSet;
27 import org.slf4j.migrator.line.JCLRuleSet;
28 import org.slf4j.migrator.line.JULRuleSet;
29 import org.slf4j.migrator.line.Log4jRuleSet;
30 import org.slf4j.migrator.line.RuleSet;
31
32 /**
33 * This class runs Pattern matching with java.util.regex using Patterns defined
34 * in concrete implementations
35 *
36 * @author jean-noelcharpin
37 *
38 */
39 public abstract class RuleSetFactory {
40
41 /**
42 * Return matcher implementation depending on the conversion mode
43 *
44 * @param conversionType
45 * @return AbstractMatcher implementation
46 */
47 public static RuleSet getMatcherImpl(int conversionType) {
48 switch (conversionType) {
49 case Constant.JCL_TO_SLF4J:
50 return new JCLRuleSet();
51 case Constant.LOG4J_TO_SLF4J:
52 return new Log4jRuleSet();
53 case Constant.JUL_TO_SLF4J:
54 return new JULRuleSet();
55 case Constant.NOP_TO_SLF4J:
56 return new EmptyRuleSet();
57 default:
58 return null;
59 }
60 }
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import org.slf4j.migrator.line.EmptyRuleSet;
27 import org.slf4j.migrator.line.JCLRuleSet;
28 import org.slf4j.migrator.line.JULRuleSet;
29 import org.slf4j.migrator.line.Log4jRuleSet;
30 import org.slf4j.migrator.line.RuleSet;
31
32 /**
33 * This class runs Pattern matching with java.util.regex using Patterns defined
34 * in concrete implementations
35 *
36 * @author jean-noelcharpin
37 *
38 */
39 public abstract class RuleSetFactory {
40
41 /**
42 * Return matcher implementation depending on the conversion mode
43 *
44 * @param conversionType
45 * @return AbstractMatcher implementation
46 */
47 public static RuleSet getMatcherImpl(int conversionType) {
48 switch (conversionType) {
49 case Constant.JCL_TO_SLF4J:
50 return new JCLRuleSet();
51 case Constant.LOG4J_TO_SLF4J:
52 return new Log4jRuleSet();
53 case Constant.JUL_TO_SLF4J:
54 return new JULRuleSet();
55 case Constant.NOP_TO_SLF4J:
56 return new EmptyRuleSet();
57 default:
58 return null;
59 }
60 }
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 public class Abbreviator {
27 static final String FILLER = "...";
28
29 final char folderSeparator;
30 final int invariantPrefixLength;
31 final int desiredLength;
32
33 public Abbreviator(int invariantPrefixLength, int desiredLength, char folderSeparator) {
34 this.invariantPrefixLength = invariantPrefixLength;
35 this.desiredLength = desiredLength;
36 this.folderSeparator = folderSeparator;
37 }
38
39 public String abbreviate(String filename) {
40 if (filename.length() <= desiredLength) {
41 return filename;
42 } else {
43
44 int firstIndex = filename.indexOf(folderSeparator, invariantPrefixLength);
45 if (firstIndex == -1) {
46 // we cant't process this string
47 return filename;
48 }
49 StringBuilder buf = new StringBuilder(desiredLength);
50 buf.append(filename, 0, firstIndex + 1);
51 buf.append(FILLER);
52 int nextIndex = computeNextIndex(filename, firstIndex);
53 if (nextIndex != -1) {
54 buf.append(filename.substring(nextIndex));
55 } else {
56 // better long than wrong
57 return filename;
58 }
59
60 if (buf.length() < filename.length()) {
61 return buf.toString();
62 } else {
63 // we tried our best but we are still could not shorten the input
64 return filename;
65 }
66 }
67 }
68
69 int computeNextIndex(String filename, int firstIndex) {
70 int nextIndex = firstIndex + 1;
71 int hitCount = 0;
72 int minToRemove = filename.length() - desiredLength + FILLER.length();
73 while (nextIndex < firstIndex + minToRemove) {
74 int tmpIndex = filename.indexOf(folderSeparator, nextIndex + 1);
75 if (tmpIndex == -1) {
76 if (hitCount == 0) {
77 return -1;
78 } else {
79 return nextIndex;
80 }
81 } else {
82 hitCount++;
83 nextIndex = tmpIndex;
84 }
85 }
86 return nextIndex;
87 }
88 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 public class Abbreviator {
27 static final String FILLER = "...";
28
29 final char folderSeparator;
30 final int invariantPrefixLength;
31 final int desiredLength;
32
33 public Abbreviator(int invariantPrefixLength, int desiredLength, char folderSeparator) {
34 this.invariantPrefixLength = invariantPrefixLength;
35 this.desiredLength = desiredLength;
36 this.folderSeparator = folderSeparator;
37 }
38
39 public String abbreviate(String filename) {
40 if (filename.length() <= desiredLength) {
41 return filename;
42 } else {
43
44 int firstIndex = filename.indexOf(folderSeparator, invariantPrefixLength);
45 if (firstIndex == -1) {
46 // we cant't process this string
47 return filename;
48 }
49 StringBuilder buf = new StringBuilder(desiredLength);
50 buf.append(filename, 0, firstIndex + 1);
51 buf.append(FILLER);
52 int nextIndex = computeNextIndex(filename, firstIndex);
53 if (nextIndex != -1) {
54 buf.append(filename.substring(nextIndex));
55 } else {
56 // better long than wrong
57 return filename;
58 }
59
60 if (buf.length() < filename.length()) {
61 return buf.toString();
62 } else {
63 // we tried our best but we are still could not shorten the input
64 return filename;
65 }
66 }
67 }
68
69 int computeNextIndex(String filename, int firstIndex) {
70 int nextIndex = firstIndex + 1;
71 int hitCount = 0;
72 int minToRemove = filename.length() - desiredLength + FILLER.length();
73 while (nextIndex < firstIndex + minToRemove) {
74 int tmpIndex = filename.indexOf(folderSeparator, nextIndex + 1);
75 if (tmpIndex == -1) {
76 if (hitCount == 0) {
77 return -1;
78 } else {
79 return nextIndex;
80 }
81 } else {
82 hitCount++;
83 nextIndex = tmpIndex;
84 }
85 }
86 return nextIndex;
87 }
88 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import java.awt.Component;
27
28 import javax.swing.SpringLayout;
29
30 public class SpringLayoutHelper {
31
32 final SpringLayout sl;
33 final int basicPadding;
34
35 public SpringLayoutHelper(SpringLayout springLayout, int basicPadding) {
36 sl = springLayout;
37 this.basicPadding = basicPadding;
38 }
39
40 public void placeToTheRight(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) {
41 sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, SpringLayout.EAST, relativeTo);
42
43 sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, SpringLayout.NORTH, relativeTo);
44 }
45
46 public void placeToTheRight(Component relativeTo, Component componentToPlace) {
47 placeToTheRight(relativeTo, componentToPlace, basicPadding, 0);
48 }
49
50 public void placeBelow(Component relativeTo, Component componentToPlace) {
51 placeBelow(relativeTo, componentToPlace, 0, basicPadding);
52 }
53
54 public void placeBelow(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) {
55 sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, SpringLayout.WEST, relativeTo);
56
57 sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, SpringLayout.SOUTH, relativeTo);
58 }
59
60 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import java.awt.Component;
27
28 import javax.swing.SpringLayout;
29
30 public class SpringLayoutHelper {
31
32 final SpringLayout sl;
33 final int basicPadding;
34
35 public SpringLayoutHelper(SpringLayout springLayout, int basicPadding) {
36 sl = springLayout;
37 this.basicPadding = basicPadding;
38 }
39
40 public void placeToTheRight(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) {
41 sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, SpringLayout.EAST, relativeTo);
42
43 sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, SpringLayout.NORTH, relativeTo);
44 }
45
46 public void placeToTheRight(Component relativeTo, Component componentToPlace) {
47 placeToTheRight(relativeTo, componentToPlace, basicPadding, 0);
48 }
49
50 public void placeBelow(Component relativeTo, Component componentToPlace) {
51 placeBelow(relativeTo, componentToPlace, 0, basicPadding);
52 }
53
54 public void placeBelow(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) {
55 sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, SpringLayout.WEST, relativeTo);
56
57 sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, SpringLayout.SOUTH, relativeTo);
58 }
59
60 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27
28 import org.slf4j.migrator.ProjectConverter;
29
30 public class ConversionTask implements Runnable {
31
32 final File folder;
33 final MigratorFrame frame;
34 final int conversionType;
35
36 ConversionTask(File folder, MigratorFrame frame, int conversionType) {
37 this.folder = folder;
38 this.frame = frame;
39 this.conversionType = conversionType;
40 }
41
42 public void run() {
43 ProgressListener pl = new ProgressListenerImpl(folder, frame);
44 pl.onMigrationBegin();
45 ProjectConverter converter = new ProjectConverter(conversionType, pl);
46 converter.convertProject(folder);
47 }
48
49 public void launch() {
50 Thread t = new Thread(this);
51 t.setDaemon(true);
52 t.start();
53 }
54
55 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27
28 import org.slf4j.migrator.ProjectConverter;
29
30 public class ConversionTask implements Runnable {
31
32 final File folder;
33 final MigratorFrame frame;
34 final int conversionType;
35
36 ConversionTask(File folder, MigratorFrame frame, int conversionType) {
37 this.folder = folder;
38 this.frame = frame;
39 this.conversionType = conversionType;
40 }
41
42 public void run() {
43 ProgressListener pl = new ProgressListenerImpl(folder, frame);
44 pl.onMigrationBegin();
45 ProjectConverter converter = new ProjectConverter(conversionType, pl);
46 converter.convertProject(folder);
47 }
48
49 public void launch() {
50 Thread t = new Thread(this);
51 t.setDaemon(true);
52 t.start();
53 }
54
55 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.awt.event.ActionEvent;
27 import java.awt.event.ActionListener;
28 import java.io.File;
29 import java.util.ArrayList;
30 import java.util.List;
31
32 import javax.swing.ButtonGroup;
33 import javax.swing.JButton;
34 import javax.swing.JCheckBox;
35 import javax.swing.JFileChooser;
36 import javax.swing.JFrame;
37 import javax.swing.JLabel;
38 import javax.swing.JOptionPane;
39 import javax.swing.JProgressBar;
40 import javax.swing.JRadioButton;
41 import javax.swing.JTextField;
42 import javax.swing.SpringLayout;
43 import javax.swing.WindowConstants;
44
45 import org.slf4j.migrator.Constant;
46 import org.slf4j.migrator.helper.SpringLayoutHelper;
47
48 public class MigratorFrame extends JFrame implements ActionListener {
49 private static final long serialVersionUID = 1L;
50
51 private static final int BASIC_PADDING = 10;
52 private static final int FOLDER_COLUMNS = 40;
53 private static final String MIGRATE_COMMAND = "MIGRATE_COMMAND";
54 private static final String BROWSE_COMMAND = "BROWSE_COMMAND";
55 static final String EXIT_COMMAND = "EXIT_COMMAND";
56
57 static final int X_SIZE = 700;
58 static final int Y_SIZE = 400;
59
60 private SpringLayout layoutManager = new SpringLayout();
61 private SpringLayoutHelper slh = new SpringLayoutHelper(layoutManager, BASIC_PADDING);
62
63 private JLabel migrationLabel;
64
65 private JRadioButton radioLog4j;
66 private JRadioButton radioJCL;
67 private JRadioButton radioJUL;
68 private ButtonGroup buttonGroup;
69
70 private JTextField folderTextField;
71 private JLabel warningLabel;
72 JButton migrateButton;
73 private JButton browseButton;
74 private JLabel folderLabel;
75
76 private JCheckBox awareCheckBox;
77 private JLabel awareLabel;
78
79 JLabel otherLabel;
80 JProgressBar progressBar;
81 private JFileChooser fileChooser;
82
83 public MigratorFrame() {
84 super();
85 initGUI();
86 }
87
88 private void initGUI() {
89 try {
90 setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
91 getContentPane().setLayout(layoutManager);
92 this.setTitle("SLF4J migrator");
93
94 createComponents();
95 constrainAll();
96 addAllComponentsToContextPane();
97 pack();
98 this.setSize(700, 400);
99 } catch (Exception e) {
100 e.printStackTrace();
101 }
102 }
103
104 private void createComponents() {
105 createMigrationLabel();
106 createRadioJCL();
107 createRadioLog4j();
108 createRadioJUL();
109 createButtonGroup();
110 createFolderLabel();
111 createFolderTextField();
112 createBrowseButton();
113 createMigrateButton();
114 createAwareCheckbox();
115 createAwareLabel();
116 createWarningLabel();
117 createFileChooser();
118
119 otherLabel = new JLabel();
120 otherLabel.setText("");
121 createProgressBar();
122
123 }
124
125 /**
126 *
127 */
128 private void constrainAll() {
129
130 // contrain migration label
131 layoutManager.putConstraint(SpringLayout.WEST, migrationLabel, BASIC_PADDING, SpringLayout.EAST, this);
132
133 layoutManager.putConstraint(SpringLayout.NORTH, migrationLabel, BASIC_PADDING, SpringLayout.NORTH, this);
134
135 slh.placeToTheRight(migrationLabel, radioJCL, BASIC_PADDING, -BASIC_PADDING / 2);
136 slh.placeBelow(radioJCL, radioLog4j, 0, 0);
137
138 slh.placeBelow(radioLog4j, radioJUL, 0, 0);
139
140 slh.placeBelow(migrationLabel, folderLabel, 0, BASIC_PADDING * 6);
141 slh.placeToTheRight(folderLabel, folderTextField);
142 slh.placeToTheRight(folderTextField, browseButton, BASIC_PADDING, -BASIC_PADDING / 2);
143
144 slh.placeBelow(folderLabel, warningLabel, 0, BASIC_PADDING * 3);
145
146 slh.placeBelow(warningLabel, awareCheckBox, 0, (int) (BASIC_PADDING * 1.5));
147 slh.placeToTheRight(awareCheckBox, awareLabel);
148
149 slh.placeBelow(awareCheckBox, migrateButton, 0, BASIC_PADDING * 3);
150
151 slh.placeBelow(migrateButton, otherLabel, 0, BASIC_PADDING * 2);
152
153 slh.placeBelow(otherLabel, progressBar, 0, BASIC_PADDING);
154 }
155
156 private void addAllComponentsToContextPane() {
157 getContentPane().add(migrationLabel);
158 getContentPane().add(radioJCL);
159 getContentPane().add(radioLog4j);
160 getContentPane().add(radioJUL);
161
162 getContentPane().add(folderLabel);
163 getContentPane().add(folderTextField);
164 getContentPane().add(browseButton);
165 getContentPane().add(migrateButton);
166
167 getContentPane().add(awareCheckBox);
168 getContentPane().add(awareLabel);
169
170 getContentPane().add(warningLabel);
171
172 getContentPane().add(otherLabel);
173 getContentPane().add(progressBar);
174 }
175
176 private void createButtonGroup() {
177 buttonGroup = new ButtonGroup();
178 buttonGroup.add(radioJCL);
179 buttonGroup.add(radioLog4j);
180 buttonGroup.add(radioJUL);
181 }
182
183 private void createMigrationLabel() {
184 migrationLabel = new JLabel();
185 migrationLabel.setText("Migration Type");
186 }
187
188 private void createRadioJCL() {
189 radioJCL = new JRadioButton();
190 radioJCL.setText("from Jakarta Commons Logging to SLF4J");
191 radioJCL.setToolTipText("Select this button if you wish to migrate a Java project using Jakarta Commons Logging to use SLF4J.");
192 }
193
194 private void createRadioLog4j() {
195 radioLog4j = new JRadioButton();
196 radioLog4j.setText("from log4j to SLF4J ");
197 radioLog4j.setToolTipText("Select this button if you wish to migrate a Java project using log4j to use SLF4J.");
198 }
199
200 private void createRadioJUL() {
201 radioJUL = new JRadioButton();
202 radioJUL.setText("from JUL to SLF4J ");
203 radioJUL.setToolTipText("Select this button if you wish to migrate a Java project using java.utl.logging (JUL) to use SLF4J.");
204 }
205
206 private void createFolderLabel() {
207 folderLabel = new JLabel();
208 folderLabel.setText("Project Directory");
209 }
210
211 private void createFolderTextField() {
212 folderTextField = new JTextField();
213 folderTextField.setColumns(FOLDER_COLUMNS);
214 }
215
216 private void createBrowseButton() {
217 browseButton = new JButton();
218 browseButton.setText("Browse");
219 browseButton.addActionListener(this);
220 browseButton.setActionCommand(BROWSE_COMMAND);
221 browseButton.setToolTipText("Click this button to browse the file systems on your computer.");
222 }
223
224 private void createAwareCheckbox() {
225 awareCheckBox = new JCheckBox();
226 awareCheckBox.setToolTipText("<html><p>Check this box of you understand that the migration tool<p>will <b>not</b> backup your Java source files.</html>");
227 }
228
229 private void createAwareLabel() {
230 awareLabel = new JLabel();
231 awareLabel.setText("<html>" + "<p>I am aware that this tool will directly modify all Java source files</p>"
232 + "<p>in the selected folder without creating backup files.</p>" + "</html>");
233 }
234
235 private void createWarningLabel() {
236 warningLabel = new JLabel();
237 warningLabel.setText("<html>" + "<p><span color=\"red\">WARNING:</span> This SLF4J migration tool will directly modify all Java source files</p>"
238 + "<p>in the selected project folder without creating a backup of the original files.</p>" + "</html>");
239 }
240
241 private void createMigrateButton() {
242 migrateButton = new JButton();
243 migrateButton.setText("Migrate Project to SLF4J");
244 migrateButton.setToolTipText("Click this button to initiate migration of your project.");
245 migrateButton.addActionListener(this);
246 migrateButton.setActionCommand(MIGRATE_COMMAND);
247 }
248
249 private void createFileChooser() {
250 fileChooser = new JFileChooser();
251 fileChooser.setDialogTitle("Source folder selector");
252 fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
253 }
254
255 private void createProgressBar() {
256 progressBar = new JProgressBar(0, 1);
257 progressBar.setPreferredSize(new java.awt.Dimension((int) (X_SIZE * 0.8), 5));
258 progressBar.setVisible(false);
259 }
260
261 public void disableInput() {
262 radioJCL.setEnabled(false);
263 radioLog4j.setEnabled(false);
264
265 browseButton.setEnabled(false);
266
267 folderTextField.setEnabled(false);
268 awareCheckBox.setEnabled(false);
269 migrateButton.setText("Migration in progress");
270 migrateButton.setEnabled(false);
271
272 }
273
274 public void actionPerformed(ActionEvent e) {
275
276 if (MIGRATE_COMMAND.equals(e.getActionCommand())) {
277
278 List<String> errorList = doSanityAnalysis();
279 if (errorList.size() > 0) {
280 showDialogBox(errorList);
281 } else {
282
283 File projectFolder = new File(folderTextField.getText());
284 int conversionType;
285 if (radioJCL.isSelected()) {
286 conversionType = Constant.JCL_TO_SLF4J;
287 } else if (radioLog4j.isSelected()) {
288 conversionType = Constant.LOG4J_TO_SLF4J;
289 } else if (radioJUL.isSelected()) {
290 conversionType = Constant.JUL_TO_SLF4J;
291 } else {
292 // we cannot possibly reach here
293 throw new IllegalStateException("One of JCL or log4j project must have been previously chosen.");
294 }
295 ConversionTask task = new ConversionTask(projectFolder, this, conversionType);
296 task.launch();
297 }
298 } else if (BROWSE_COMMAND.equals(e.getActionCommand())) {
299 showFileChooser();
300 } else if (EXIT_COMMAND.equals(e.getActionCommand())) {
301 this.dispose();
302 }
303 }
304
305 void showFileChooser() {
306 int returnVal = fileChooser.showOpenDialog(this);
307 if (returnVal == JFileChooser.APPROVE_OPTION) {
308 File selectedFile = fileChooser.getSelectedFile();
309 folderTextField.setText(selectedFile.getAbsolutePath());
310 }
311 }
312
313 List<String> doSanityAnalysis() {
314
315 List<String> errorList = new ArrayList<String>();
316 if (!radioJCL.isSelected() && !radioLog4j.isSelected() && !radioJUL.isSelected()) {
317 errorList.add("Please select the migration type: JCL, log4j, or JUL to SLF4J.");
318 }
319
320 String folder = folderTextField.getText();
321
322 if (folder == null || folder.length() == 0) {
323 errorList.add("Please select the folder of the project to migrate");
324 } else if (!isDirectory(folder)) {
325 errorList.add("[" + folder + "] does not look like a valid folder");
326 }
327
328 if (!awareCheckBox.isSelected()) {
329 errorList.add("Cannot initiate migration unless you acknowledge<p>that files will be modified without creating backup files");
330 }
331 return errorList;
332 }
333
334 void showDialogBox(List<String> errorList) {
335 StringBuilder buf = new StringBuilder();
336 buf.append("<html>");
337 int i = 1;
338 for (String msg : errorList) {
339 buf.append("<p>");
340 buf.append(i);
341 buf.append(". ");
342 buf.append(msg);
343 buf.append("</p>");
344 i++;
345 }
346 buf.append("</html>");
347
348 JOptionPane.showMessageDialog(this, buf.toString(), "", JOptionPane.ERROR_MESSAGE);
349 }
350
351 boolean isDirectory(String filename) {
352 if (filename == null) {
353 return false;
354 }
355 File file = new File(filename);
356 if (file.exists() && file.isDirectory()) {
357 return true;
358 } else {
359 return false;
360 }
361 }
362 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.awt.event.ActionEvent;
27 import java.awt.event.ActionListener;
28 import java.io.File;
29 import java.util.ArrayList;
30 import java.util.List;
31
32 import javax.swing.ButtonGroup;
33 import javax.swing.JButton;
34 import javax.swing.JCheckBox;
35 import javax.swing.JFileChooser;
36 import javax.swing.JFrame;
37 import javax.swing.JLabel;
38 import javax.swing.JOptionPane;
39 import javax.swing.JProgressBar;
40 import javax.swing.JRadioButton;
41 import javax.swing.JTextField;
42 import javax.swing.SpringLayout;
43 import javax.swing.WindowConstants;
44
45 import org.slf4j.migrator.Constant;
46 import org.slf4j.migrator.helper.SpringLayoutHelper;
47
48 public class MigratorFrame extends JFrame implements ActionListener {
49 private static final long serialVersionUID = 1L;
50
51 private static final int BASIC_PADDING = 10;
52 private static final int FOLDER_COLUMNS = 40;
53 private static final String MIGRATE_COMMAND = "MIGRATE_COMMAND";
54 private static final String BROWSE_COMMAND = "BROWSE_COMMAND";
55 static final String EXIT_COMMAND = "EXIT_COMMAND";
56
57 static final int X_SIZE = 700;
58 static final int Y_SIZE = 400;
59
60 private SpringLayout layoutManager = new SpringLayout();
61 private SpringLayoutHelper slh = new SpringLayoutHelper(layoutManager, BASIC_PADDING);
62
63 private JLabel migrationLabel;
64
65 private JRadioButton radioLog4j;
66 private JRadioButton radioJCL;
67 private JRadioButton radioJUL;
68 private ButtonGroup buttonGroup;
69
70 private JTextField folderTextField;
71 private JLabel warningLabel;
72 JButton migrateButton;
73 private JButton browseButton;
74 private JLabel folderLabel;
75
76 private JCheckBox awareCheckBox;
77 private JLabel awareLabel;
78
79 JLabel otherLabel;
80 JProgressBar progressBar;
81 private JFileChooser fileChooser;
82
83 public MigratorFrame() {
84 super();
85 initGUI();
86 }
87
88 private void initGUI() {
89 try {
90 setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
91 getContentPane().setLayout(layoutManager);
92 this.setTitle("SLF4J migrator");
93
94 createComponents();
95 constrainAll();
96 addAllComponentsToContextPane();
97 pack();
98 this.setSize(700, 400);
99 } catch (Exception e) {
100 e.printStackTrace();
101 }
102 }
103
104 private void createComponents() {
105 createMigrationLabel();
106 createRadioJCL();
107 createRadioLog4j();
108 createRadioJUL();
109 createButtonGroup();
110 createFolderLabel();
111 createFolderTextField();
112 createBrowseButton();
113 createMigrateButton();
114 createAwareCheckbox();
115 createAwareLabel();
116 createWarningLabel();
117 createFileChooser();
118
119 otherLabel = new JLabel();
120 otherLabel.setText("");
121 createProgressBar();
122
123 }
124
125 /**
126 *
127 */
128 private void constrainAll() {
129
130 // contrain migration label
131 layoutManager.putConstraint(SpringLayout.WEST, migrationLabel, BASIC_PADDING, SpringLayout.EAST, this);
132
133 layoutManager.putConstraint(SpringLayout.NORTH, migrationLabel, BASIC_PADDING, SpringLayout.NORTH, this);
134
135 slh.placeToTheRight(migrationLabel, radioJCL, BASIC_PADDING, -BASIC_PADDING / 2);
136 slh.placeBelow(radioJCL, radioLog4j, 0, 0);
137
138 slh.placeBelow(radioLog4j, radioJUL, 0, 0);
139
140 slh.placeBelow(migrationLabel, folderLabel, 0, BASIC_PADDING * 6);
141 slh.placeToTheRight(folderLabel, folderTextField);
142 slh.placeToTheRight(folderTextField, browseButton, BASIC_PADDING, -BASIC_PADDING / 2);
143
144 slh.placeBelow(folderLabel, warningLabel, 0, BASIC_PADDING * 3);
145
146 slh.placeBelow(warningLabel, awareCheckBox, 0, (int) (BASIC_PADDING * 1.5));
147 slh.placeToTheRight(awareCheckBox, awareLabel);
148
149 slh.placeBelow(awareCheckBox, migrateButton, 0, BASIC_PADDING * 3);
150
151 slh.placeBelow(migrateButton, otherLabel, 0, BASIC_PADDING * 2);
152
153 slh.placeBelow(otherLabel, progressBar, 0, BASIC_PADDING);
154 }
155
156 private void addAllComponentsToContextPane() {
157 getContentPane().add(migrationLabel);
158 getContentPane().add(radioJCL);
159 getContentPane().add(radioLog4j);
160 getContentPane().add(radioJUL);
161
162 getContentPane().add(folderLabel);
163 getContentPane().add(folderTextField);
164 getContentPane().add(browseButton);
165 getContentPane().add(migrateButton);
166
167 getContentPane().add(awareCheckBox);
168 getContentPane().add(awareLabel);
169
170 getContentPane().add(warningLabel);
171
172 getContentPane().add(otherLabel);
173 getContentPane().add(progressBar);
174 }
175
176 private void createButtonGroup() {
177 buttonGroup = new ButtonGroup();
178 buttonGroup.add(radioJCL);
179 buttonGroup.add(radioLog4j);
180 buttonGroup.add(radioJUL);
181 }
182
183 private void createMigrationLabel() {
184 migrationLabel = new JLabel();
185 migrationLabel.setText("Migration Type");
186 }
187
188 private void createRadioJCL() {
189 radioJCL = new JRadioButton();
190 radioJCL.setText("from Jakarta Commons Logging to SLF4J");
191 radioJCL.setToolTipText("Select this button if you wish to migrate a Java project using Jakarta Commons Logging to use SLF4J.");
192 }
193
194 private void createRadioLog4j() {
195 radioLog4j = new JRadioButton();
196 radioLog4j.setText("from log4j to SLF4J ");
197 radioLog4j.setToolTipText("Select this button if you wish to migrate a Java project using log4j to use SLF4J.");
198 }
199
200 private void createRadioJUL() {
201 radioJUL = new JRadioButton();
202 radioJUL.setText("from JUL to SLF4J ");
203 radioJUL.setToolTipText("Select this button if you wish to migrate a Java project using java.utl.logging (JUL) to use SLF4J.");
204 }
205
206 private void createFolderLabel() {
207 folderLabel = new JLabel();
208 folderLabel.setText("Project Directory");
209 }
210
211 private void createFolderTextField() {
212 folderTextField = new JTextField();
213 folderTextField.setColumns(FOLDER_COLUMNS);
214 }
215
216 private void createBrowseButton() {
217 browseButton = new JButton();
218 browseButton.setText("Browse");
219 browseButton.addActionListener(this);
220 browseButton.setActionCommand(BROWSE_COMMAND);
221 browseButton.setToolTipText("Click this button to browse the file systems on your computer.");
222 }
223
224 private void createAwareCheckbox() {
225 awareCheckBox = new JCheckBox();
226 awareCheckBox.setToolTipText("<html><p>Check this box of you understand that the migration tool<p>will <b>not</b> backup your Java source files.</html>");
227 }
228
229 private void createAwareLabel() {
230 awareLabel = new JLabel();
231 awareLabel.setText("<html>" + "<p>I am aware that this tool will directly modify all Java source files</p>"
232 + "<p>in the selected folder without creating backup files.</p>" + "</html>");
233 }
234
235 private void createWarningLabel() {
236 warningLabel = new JLabel();
237 warningLabel.setText("<html>" + "<p><span color=\"red\">WARNING:</span> This SLF4J migration tool will directly modify all Java source files</p>"
238 + "<p>in the selected project folder without creating a backup of the original files.</p>" + "</html>");
239 }
240
241 private void createMigrateButton() {
242 migrateButton = new JButton();
243 migrateButton.setText("Migrate Project to SLF4J");
244 migrateButton.setToolTipText("Click this button to initiate migration of your project.");
245 migrateButton.addActionListener(this);
246 migrateButton.setActionCommand(MIGRATE_COMMAND);
247 }
248
249 private void createFileChooser() {
250 fileChooser = new JFileChooser();
251 fileChooser.setDialogTitle("Source folder selector");
252 fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
253 }
254
255 private void createProgressBar() {
256 progressBar = new JProgressBar(0, 1);
257 progressBar.setPreferredSize(new java.awt.Dimension((int) (X_SIZE * 0.8), 5));
258 progressBar.setVisible(false);
259 }
260
261 public void disableInput() {
262 radioJCL.setEnabled(false);
263 radioLog4j.setEnabled(false);
264
265 browseButton.setEnabled(false);
266
267 folderTextField.setEnabled(false);
268 awareCheckBox.setEnabled(false);
269 migrateButton.setText("Migration in progress");
270 migrateButton.setEnabled(false);
271
272 }
273
274 public void actionPerformed(ActionEvent e) {
275
276 if (MIGRATE_COMMAND.equals(e.getActionCommand())) {
277
278 List<String> errorList = doSanityAnalysis();
279 if (errorList.size() > 0) {
280 showDialogBox(errorList);
281 } else {
282
283 File projectFolder = new File(folderTextField.getText());
284 int conversionType;
285 if (radioJCL.isSelected()) {
286 conversionType = Constant.JCL_TO_SLF4J;
287 } else if (radioLog4j.isSelected()) {
288 conversionType = Constant.LOG4J_TO_SLF4J;
289 } else if (radioJUL.isSelected()) {
290 conversionType = Constant.JUL_TO_SLF4J;
291 } else {
292 // we cannot possibly reach here
293 throw new IllegalStateException("One of JCL or log4j project must have been previously chosen.");
294 }
295 ConversionTask task = new ConversionTask(projectFolder, this, conversionType);
296 task.launch();
297 }
298 } else if (BROWSE_COMMAND.equals(e.getActionCommand())) {
299 showFileChooser();
300 } else if (EXIT_COMMAND.equals(e.getActionCommand())) {
301 this.dispose();
302 }
303 }
304
305 void showFileChooser() {
306 int returnVal = fileChooser.showOpenDialog(this);
307 if (returnVal == JFileChooser.APPROVE_OPTION) {
308 File selectedFile = fileChooser.getSelectedFile();
309 folderTextField.setText(selectedFile.getAbsolutePath());
310 }
311 }
312
313 List<String> doSanityAnalysis() {
314
315 List<String> errorList = new ArrayList<String>();
316 if (!radioJCL.isSelected() && !radioLog4j.isSelected() && !radioJUL.isSelected()) {
317 errorList.add("Please select the migration type: JCL, log4j, or JUL to SLF4J.");
318 }
319
320 String folder = folderTextField.getText();
321
322 if (folder == null || folder.length() == 0) {
323 errorList.add("Please select the folder of the project to migrate");
324 } else if (!isDirectory(folder)) {
325 errorList.add("[" + folder + "] does not look like a valid folder");
326 }
327
328 if (!awareCheckBox.isSelected()) {
329 errorList.add("Cannot initiate migration unless you acknowledge<p>that files will be modified without creating backup files");
330 }
331 return errorList;
332 }
333
334 void showDialogBox(List<String> errorList) {
335 StringBuilder buf = new StringBuilder();
336 buf.append("<html>");
337 int i = 1;
338 for (String msg : errorList) {
339 buf.append("<p>");
340 buf.append(i);
341 buf.append(". ");
342 buf.append(msg);
343 buf.append("</p>");
344 i++;
345 }
346 buf.append("</html>");
347
348 JOptionPane.showMessageDialog(this, buf.toString(), "", JOptionPane.ERROR_MESSAGE);
349 }
350
351 boolean isDirectory(String filename) {
352 if (filename == null) {
353 return false;
354 }
355 File file = new File(filename);
356 if (file.exists() && file.isDirectory()) {
357 return true;
358 } else {
359 return false;
360 }
361 }
362 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27
28 public interface ProgressListener {
29
30 public void onMigrationBegin();
31
32 public void onDirectory(File file);
33
34 public void onFileAddition(File file);
35
36 public void onFileScanBegin();
37
38 public void onFileScan(File file);
39
40 public void onInplaceConversion(File file);
41
42 public void onDone();
43
44 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27
28 public interface ProgressListener {
29
30 public void onMigrationBegin();
31
32 public void onDirectory(File file);
33
34 public void onFileAddition(File file);
35
36 public void onFileScanBegin();
37
38 public void onFileScan(File file);
39
40 public void onInplaceConversion(File file);
41
42 public void onDone();
43
44 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27 import java.io.IOException;
28
29 import org.slf4j.migrator.helper.Abbreviator;
30
31 public class ProgressListenerImpl implements ProgressListener {
32
33 static final int TARGET_FILE_LENGTH = 85;
34 static final int UPDATE_THRESHOLD = 100;
35
36 int addFileCount = 0;
37 int scanFileCount = 0;
38 int inplaceConversionCount = 0;
39 final MigratorFrame frame;
40
41 Abbreviator abbr;
42
43 long lastUpdate = 0;
44
45 public ProgressListenerImpl(File projectFolder, MigratorFrame frame) {
46 this.frame = frame;
47 this.abbr = new Abbreviator((int) projectFolder.length(), TARGET_FILE_LENGTH, File.separatorChar);
48 }
49
50 public void onMigrationBegin() {
51 frame.disableInput();
52 }
53
54 boolean isTooSoon() {
55 long now = System.currentTimeMillis();
56 if (now - lastUpdate < UPDATE_THRESHOLD) {
57 return true;
58 } else {
59 lastUpdate = now;
60 return false;
61 }
62 }
63
64 public void onDirectory(File file) {
65 if (isTooSoon())
66 return;
67
68 String abbreviatedName = getShortName(file);
69 frame.otherLabel.setText("<html><p>Searching folder [" + abbreviatedName + "]<p>Found " + addFileCount + " java files to scan.</html>");
70 }
71
72 public void onDone() {
73 frame.progressBar.setVisible(false);
74 frame.otherLabel.setText("<html><font color='BLUE'>Scanned " + addFileCount + " java files, " + inplaceConversionCount
75 + " files were modified.</font></html>");
76
77 frame.migrateButton.setActionCommand(MigratorFrame.EXIT_COMMAND);
78 frame.migrateButton.setText("Exit");
79 frame.migrateButton.setToolTipText("Click on this button to exit this application.");
80 frame.migrateButton.setEnabled(true);
81
82 }
83
84 public void onFileAddition(File file) {
85 addFileCount++;
86 }
87
88 public void onFileScan(File file) {
89
90 scanFileCount++;
91 if (isTooSoon())
92 return;
93 String abbreviatedName = getShortName(file);
94
95 frame.otherLabel.setText("<html><p>Scanning file [" + abbreviatedName + "]<p></html>");
96 // File + scanFileCount + " out of "+ addFileCount+" files to scan."+
97 // inplaceConversionCount+ " files converted." +
98
99 frame.progressBar.setValue(scanFileCount);
100 }
101
102 public void onInplaceConversion(File file) {
103 inplaceConversionCount++;
104 }
105
106 String getShortName(File file) {
107 try {
108 return abbr.abbreviate(file.getCanonicalPath());
109 } catch (IOException e) {
110 return file.toString();
111 }
112 }
113
114 public void onFileScanBegin() {
115 frame.progressBar.setMaximum(addFileCount);
116 frame.progressBar.setValue(0);
117 frame.progressBar.setVisible(true);
118 }
119
120 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27 import java.io.IOException;
28
29 import org.slf4j.migrator.helper.Abbreviator;
30
31 public class ProgressListenerImpl implements ProgressListener {
32
33 static final int TARGET_FILE_LENGTH = 85;
34 static final int UPDATE_THRESHOLD = 100;
35
36 int addFileCount = 0;
37 int scanFileCount = 0;
38 int inplaceConversionCount = 0;
39 final MigratorFrame frame;
40
41 Abbreviator abbr;
42
43 long lastUpdate = 0;
44
45 public ProgressListenerImpl(File projectFolder, MigratorFrame frame) {
46 this.frame = frame;
47 this.abbr = new Abbreviator((int) projectFolder.length(), TARGET_FILE_LENGTH, File.separatorChar);
48 }
49
50 public void onMigrationBegin() {
51 frame.disableInput();
52 }
53
54 boolean isTooSoon() {
55 long now = System.currentTimeMillis();
56 if (now - lastUpdate < UPDATE_THRESHOLD) {
57 return true;
58 } else {
59 lastUpdate = now;
60 return false;
61 }
62 }
63
64 public void onDirectory(File file) {
65 if (isTooSoon())
66 return;
67
68 String abbreviatedName = getShortName(file);
69 frame.otherLabel.setText("<html><p>Searching folder [" + abbreviatedName + "]<p>Found " + addFileCount + " java files to scan.</html>");
70 }
71
72 public void onDone() {
73 frame.progressBar.setVisible(false);
74 frame.otherLabel.setText("<html><font color='BLUE'>Scanned " + addFileCount + " java files, " + inplaceConversionCount
75 + " files were modified.</font></html>");
76
77 frame.migrateButton.setActionCommand(MigratorFrame.EXIT_COMMAND);
78 frame.migrateButton.setText("Exit");
79 frame.migrateButton.setToolTipText("Click on this button to exit this application.");
80 frame.migrateButton.setEnabled(true);
81
82 }
83
84 public void onFileAddition(File file) {
85 addFileCount++;
86 }
87
88 public void onFileScan(File file) {
89
90 scanFileCount++;
91 if (isTooSoon())
92 return;
93 String abbreviatedName = getShortName(file);
94
95 frame.otherLabel.setText("<html><p>Scanning file [" + abbreviatedName + "]<p></html>");
96 // File + scanFileCount + " out of "+ addFileCount+" files to scan."+
97 // inplaceConversionCount+ " files converted." +
98
99 frame.progressBar.setValue(scanFileCount);
100 }
101
102 public void onInplaceConversion(File file) {
103 inplaceConversionCount++;
104 }
105
106 String getShortName(File file) {
107 try {
108 return abbr.abbreviate(file.getCanonicalPath());
109 } catch (IOException e) {
110 return file.toString();
111 }
112 }
113
114 public void onFileScanBegin() {
115 frame.progressBar.setMaximum(addFileCount);
116 frame.progressBar.setValue(0);
117 frame.progressBar.setVisible(true);
118 }
119
120 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 public interface ConversionRule {
30
31 public Pattern getPattern();
32
33 /**
34 * Given replacement rules, replace each capturing group in matcher's pattern
35 *
36 * @param matcher
37 * @return String
38 */
39 public String replace(Matcher matcher);
40
41 /**
42 * Returns a non-null value if there should be an additional line
43 * following a match of this rule. In most cases this method
44 * returns null.
45 *
46 * @return String
47 */
48 public String getAdditionalLine();
49
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 public interface ConversionRule {
30
31 public Pattern getPattern();
32
33 /**
34 * Given replacement rules, replace each capturing group in matcher's pattern
35 *
36 * @param matcher
37 * @return String
38 */
39 public String replace(Matcher matcher);
40
41 /**
42 * Returns a non-null value if there should be an additional line
43 * following a match of this rule. In most cases this method
44 * returns null.
45 *
46 * @return String
47 */
48 public String getAdditionalLine();
49
5050 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.List;
29
30 public class EmptyRuleSet implements RuleSet {
31
32 List<ConversionRule> list = new ArrayList<ConversionRule>();
33
34 public Iterator<ConversionRule> iterator() {
35 return list.iterator();
36 }
37
38 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.List;
29
30 public class EmptyRuleSet implements RuleSet {
31
32 List<ConversionRule> list = new ArrayList<ConversionRule>();
33
34 public Iterator<ConversionRule> iterator() {
35 return list.iterator();
36 }
37
38 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 /**
31 * This class represents JCL to SLF4J conversion rules
32 *
33 * @author Jean-Noel Charpin
34 *
35 */
36 public class JCLRuleSet implements RuleSet {
37
38 private ArrayList<ConversionRule> conversionRuleList;
39
40 public JCLRuleSet() {
41 // matching : import org.apache.commons.logging.LogFactory;
42 SingleConversionRule cr0 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.commons.logging.LogFactory;"),
43 "import org.slf4j.LoggerFactory;");
44
45 // matching : import org.apache.commons.logging.Log;
46 SingleConversionRule cr1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.commons.logging.Log;"), "import org.slf4j.Logger;");
47
48 SingleConversionRule cr2 = new SingleConversionRule(Pattern.compile("(\\sLog\\b)"), " Logger");
49
50 SingleConversionRule cr3 = new SingleConversionRule(Pattern.compile("(^Log\\b)"), "Logger");
51
52 SingleConversionRule cr4 = new SingleConversionRule(Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("), "LoggerFactory.getLogger(");
53
54 SingleConversionRule cr5 = new SingleConversionRule(Pattern.compile("LogFactory.getLog\\("), "LoggerFactory.getLogger(");
55
56 conversionRuleList = new ArrayList<ConversionRule>();
57 conversionRuleList.add(cr0);
58 conversionRuleList.add(cr1);
59 conversionRuleList.add(cr2);
60 conversionRuleList.add(cr3);
61 conversionRuleList.add(cr4);
62 conversionRuleList.add(cr5);
63 }
64
65 public Iterator<ConversionRule> iterator() {
66 return conversionRuleList.iterator();
67 }
68 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 /**
31 * This class represents JCL to SLF4J conversion rules
32 *
33 * @author Jean-Noel Charpin
34 *
35 */
36 public class JCLRuleSet implements RuleSet {
37
38 private ArrayList<ConversionRule> conversionRuleList;
39
40 public JCLRuleSet() {
41 // matching : import org.apache.commons.logging.LogFactory;
42 SingleConversionRule cr0 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.commons.logging.LogFactory;"),
43 "import org.slf4j.LoggerFactory;");
44
45 // matching : import org.apache.commons.logging.Log;
46 SingleConversionRule cr1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.commons.logging.Log;"), "import org.slf4j.Logger;");
47
48 SingleConversionRule cr2 = new SingleConversionRule(Pattern.compile("(\\sLog\\b)"), " Logger");
49
50 SingleConversionRule cr3 = new SingleConversionRule(Pattern.compile("(^Log\\b)"), "Logger");
51
52 SingleConversionRule cr4 = new SingleConversionRule(Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("), "LoggerFactory.getLogger(");
53
54 SingleConversionRule cr5 = new SingleConversionRule(Pattern.compile("LogFactory.getLog\\("), "LoggerFactory.getLogger(");
55
56 conversionRuleList = new ArrayList<ConversionRule>();
57 conversionRuleList.add(cr0);
58 conversionRuleList.add(cr1);
59 conversionRuleList.add(cr2);
60 conversionRuleList.add(cr3);
61 conversionRuleList.add(cr4);
62 conversionRuleList.add(cr5);
63 }
64
65 public Iterator<ConversionRule> iterator() {
66 return conversionRuleList.iterator();
67 }
68 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 /**
31 * This class represents java.util.logging (JUL) to SLF4J conversion rules
32 *
33 * @author Jean-Noel Charpin
34 * @author Ceki Gulcu
35 */
36 public class JULRuleSet implements RuleSet {
37
38 private ArrayList<ConversionRule> conversionRuleList;
39
40 public JULRuleSet() {
41
42 SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.Logger;"), "import org.slf4j.Logger;",
43 "import org.slf4j.LoggerFactory;");
44
45 SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;");
46
47 SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.*;"), "import org.slf4j.Logger;",
48 "import org.slf4j.LoggerFactory;");
49
50 SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger(");
51
52 SingleConversionRule crFactory1 = new SingleConversionRule(Pattern.compile("LogManager.getLogger\\("), "LoggerFactory.getLogger(");
53
54 SingleConversionRule crWarning = new SingleConversionRule(Pattern.compile("\\.warning\\("), ".warn(");
55 SingleConversionRule crSevere = new SingleConversionRule(Pattern.compile("\\.severe\\("), ".error(");
56
57 conversionRuleList = new ArrayList<ConversionRule>();
58 conversionRuleList.add(crImport0);
59 conversionRuleList.add(crImport1);
60 conversionRuleList.add(crImport2);
61 conversionRuleList.add(crFactory0);
62 conversionRuleList.add(crFactory1);
63 conversionRuleList.add(crWarning);
64 conversionRuleList.add(crSevere);
65 }
66
67 public Iterator<ConversionRule> iterator() {
68 return conversionRuleList.iterator();
69 }
70
71 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 /**
31 * This class represents java.util.logging (JUL) to SLF4J conversion rules
32 *
33 * @author Jean-Noel Charpin
34 * @author Ceki Gulcu
35 */
36 public class JULRuleSet implements RuleSet {
37
38 private ArrayList<ConversionRule> conversionRuleList;
39
40 public JULRuleSet() {
41
42 SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.Logger;"), "import org.slf4j.Logger;",
43 "import org.slf4j.LoggerFactory;");
44
45 SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;");
46
47 SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.*;"), "import org.slf4j.Logger;",
48 "import org.slf4j.LoggerFactory;");
49
50 SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger(");
51
52 SingleConversionRule crFactory1 = new SingleConversionRule(Pattern.compile("LogManager.getLogger\\("), "LoggerFactory.getLogger(");
53
54 SingleConversionRule crWarning = new SingleConversionRule(Pattern.compile("\\.warning\\("), ".warn(");
55 SingleConversionRule crSevere = new SingleConversionRule(Pattern.compile("\\.severe\\("), ".error(");
56
57 conversionRuleList = new ArrayList<ConversionRule>();
58 conversionRuleList.add(crImport0);
59 conversionRuleList.add(crImport1);
60 conversionRuleList.add(crImport2);
61 conversionRuleList.add(crFactory0);
62 conversionRuleList.add(crFactory1);
63 conversionRuleList.add(crWarning);
64 conversionRuleList.add(crSevere);
65 }
66
67 public Iterator<ConversionRule> iterator() {
68 return conversionRuleList.iterator();
69 }
70
71 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.Arrays;
27 import java.util.Iterator;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30
31 public class LineConverter {
32
33 final RuleSet ruleSet;
34 boolean atLeastOneMatchOccured = false;
35
36 public LineConverter(RuleSet ruleSet) {
37 this.ruleSet = ruleSet;
38 }
39
40 /**
41 * Check if the specified text is matching some conversions rules.
42 * If a rule matches, ask for line replacement.
43 *
44 * <p>In case no rule can be applied, then the input text is
45 * returned without change.
46 *
47 * @param text
48 * @return String
49 */
50 public String[] getReplacement(String text) {
51 ConversionRule conversionRule;
52 Pattern pattern;
53 Matcher matcher;
54 Iterator<ConversionRule> conversionRuleIterator = ruleSet.iterator();
55 String additionalLine = null;
56 while (conversionRuleIterator.hasNext()) {
57 conversionRule = conversionRuleIterator.next();
58 pattern = conversionRule.getPattern();
59 matcher = pattern.matcher(text);
60 if (matcher.find()) {
61 // System.out.println("matching " + text);
62 atLeastOneMatchOccured = true;
63 String replacementText = conversionRule.replace(matcher);
64 text = matcher.replaceAll(replacementText);
65 if (conversionRule.getAdditionalLine() != null) {
66 additionalLine = conversionRule.getAdditionalLine();
67 }
68 }
69 }
70
71 if (additionalLine == null) {
72 return new String[] { text };
73 } else {
74 return new String[] { text, additionalLine };
75 }
76 }
77
78 public String getOneLineReplacement(String text) {
79 String[] r = getReplacement(text);
80 if (r.length != 1) {
81 throw new IllegalStateException("Expecting a single string but got " + Arrays.toString(r));
82 } else {
83 return r[0];
84 }
85 }
86
87 public boolean atLeastOneMatchOccured() {
88 return atLeastOneMatchOccured;
89 }
90 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.Arrays;
27 import java.util.Iterator;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30
31 public class LineConverter {
32
33 final RuleSet ruleSet;
34 boolean atLeastOneMatchOccured = false;
35
36 public LineConverter(RuleSet ruleSet) {
37 this.ruleSet = ruleSet;
38 }
39
40 /**
41 * Check if the specified text is matching some conversions rules.
42 * If a rule matches, ask for line replacement.
43 *
44 * <p>In case no rule can be applied, then the input text is
45 * returned without change.
46 *
47 * @param text
48 * @return String
49 */
50 public String[] getReplacement(String text) {
51 ConversionRule conversionRule;
52 Pattern pattern;
53 Matcher matcher;
54 Iterator<ConversionRule> conversionRuleIterator = ruleSet.iterator();
55 String additionalLine = null;
56 while (conversionRuleIterator.hasNext()) {
57 conversionRule = conversionRuleIterator.next();
58 pattern = conversionRule.getPattern();
59 matcher = pattern.matcher(text);
60 if (matcher.find()) {
61 // System.out.println("matching " + text);
62 atLeastOneMatchOccured = true;
63 String replacementText = conversionRule.replace(matcher);
64 text = matcher.replaceAll(replacementText);
65 if (conversionRule.getAdditionalLine() != null) {
66 additionalLine = conversionRule.getAdditionalLine();
67 }
68 }
69 }
70
71 if (additionalLine == null) {
72 return new String[] { text };
73 } else {
74 return new String[] { text, additionalLine };
75 }
76 }
77
78 public String getOneLineReplacement(String text) {
79 String[] r = getReplacement(text);
80 if (r.length != 1) {
81 throw new IllegalStateException("Expecting a single string but got " + Arrays.toString(r));
82 } else {
83 return r[0];
84 }
85 }
86
87 public boolean atLeastOneMatchOccured() {
88 return atLeastOneMatchOccured;
89 }
90 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 public class Log4jRuleSet implements RuleSet {
31
32 private ArrayList<ConversionRule> conversionRuleList;
33
34 public Log4jRuleSet() {
35
36 SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.Logger;"), "import org.slf4j.Logger;",
37 "import org.slf4j.LoggerFactory;");
38
39 SingleConversionRule catImport = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.Category;"), "import org.slf4j.Logger;",
40 "import org.slf4j.LoggerFactory;");
41
42 SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;");
43
44 SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.*;"), "import org.slf4j.Logger;",
45 "import org.slf4j.LoggerFactory;");
46
47 SingleConversionRule crImportMDC = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.MDC;"), "import org.slf4j.MDC;");
48
49 SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger(");
50
51 SingleConversionRule crFactory1 = new SingleConversionRule(Pattern.compile("\\sCategory.getInstance\\("), " LoggerFactory.getLogger(");
52
53 SingleConversionRule crFactory2 = new SingleConversionRule(Pattern.compile("LogManager.getLogger\\("), "LoggerFactory.getLogger(");
54
55 SingleConversionRule variable0 = new SingleConversionRule(Pattern.compile("(\\sCategory\\b)"), " Logger");
56
57 SingleConversionRule variable1 = new SingleConversionRule(Pattern.compile("(^Category\\b)"), "Logger");
58
59 conversionRuleList = new ArrayList<ConversionRule>();
60 conversionRuleList.add(crImport0);
61 conversionRuleList.add(catImport);
62 conversionRuleList.add(crImport1);
63 conversionRuleList.add(crImport2);
64 conversionRuleList.add(crImportMDC);
65 conversionRuleList.add(crFactory0);
66 conversionRuleList.add(crFactory1);
67 conversionRuleList.add(crFactory2);
68
69 conversionRuleList.add(variable0);
70 conversionRuleList.add(variable1);
71 }
72
73 public Iterator<ConversionRule> iterator() {
74 return conversionRuleList.iterator();
75 }
76
77 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 public class Log4jRuleSet implements RuleSet {
31
32 private ArrayList<ConversionRule> conversionRuleList;
33
34 public Log4jRuleSet() {
35
36 SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.Logger;"), "import org.slf4j.Logger;",
37 "import org.slf4j.LoggerFactory;");
38
39 SingleConversionRule catImport = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.Category;"), "import org.slf4j.Logger;",
40 "import org.slf4j.LoggerFactory;");
41
42 SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;");
43
44 SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.*;"), "import org.slf4j.Logger;",
45 "import org.slf4j.LoggerFactory;");
46
47 SingleConversionRule crImportMDC = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.MDC;"), "import org.slf4j.MDC;");
48
49 SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger(");
50
51 SingleConversionRule crFactory1 = new SingleConversionRule(Pattern.compile("\\sCategory.getInstance\\("), " LoggerFactory.getLogger(");
52
53 SingleConversionRule crFactory2 = new SingleConversionRule(Pattern.compile("LogManager.getLogger\\("), "LoggerFactory.getLogger(");
54
55 SingleConversionRule variable0 = new SingleConversionRule(Pattern.compile("(\\sCategory\\b)"), " Logger");
56
57 SingleConversionRule variable1 = new SingleConversionRule(Pattern.compile("(^Category\\b)"), "Logger");
58
59 conversionRuleList = new ArrayList<ConversionRule>();
60 conversionRuleList.add(crImport0);
61 conversionRuleList.add(catImport);
62 conversionRuleList.add(crImport1);
63 conversionRuleList.add(crImport2);
64 conversionRuleList.add(crImportMDC);
65 conversionRuleList.add(crFactory0);
66 conversionRuleList.add(crFactory1);
67 conversionRuleList.add(crFactory2);
68
69 conversionRuleList.add(variable0);
70 conversionRuleList.add(variable1);
71 }
72
73 public Iterator<ConversionRule> iterator() {
74 return conversionRuleList.iterator();
75 }
76
77 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 /**
30 * This class represents a conversion rule It uses a Pattern and defines for
31 * each capturing group of this Pattern a replacement text
32 *
33 * @author jean-noelcharpin
34 *
35 */
36 public class MultiGroupConversionRule implements ConversionRule {
37
38 // It is extremely unlikely to encounter more than 10 groups in one of
39 // our conversion reg-expressions
40 final private static int MAX_GROUPS = 10;
41
42 private Pattern pattern;
43 private String[] replacementTable = new String[MAX_GROUPS];
44
45 public MultiGroupConversionRule(Pattern pattern) {
46 this.pattern = pattern;
47 }
48
49 /*
50 * (non-Javadoc)
51 *
52 * @see org.slf4j.converter.ConversionRule#getPattern()
53 */
54 public Pattern getPattern() {
55 return pattern;
56 }
57
58 public void addReplacement(int groupIndex, String replacement) {
59 if (groupIndex == 0) {
60 throw new IllegalArgumentException("regex groups start at 1, not zero");
61 }
62 replacementTable[groupIndex] = replacement;
63 }
64
65 /*
66 * (non-Javadoc)
67 *
68 * @see org.slf4j.converter.ConversionRule#getReplacement(java.lang.Integer)
69 */
70 public String getReplacement(int groupIndex) {
71 return replacementTable[groupIndex];
72 }
73
74 /*
75 * (non-Javadoc)
76 *
77 * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher)
78 */
79 public String replace(Matcher matcher) {
80 StringBuilder replacementBuffer = new StringBuilder();
81 String replacementText;
82
83 for (int group = 1; group <= matcher.groupCount(); group++) {
84 replacementText = getReplacement(group);
85 if (replacementText != null) {
86 // System.out.println("replacing group " + group + " : "
87 // + matcher.group(group) + " with " + replacementText);
88 replacementBuffer.append(replacementText);
89 } else {
90 replacementBuffer.append(matcher.group(group));
91 }
92 }
93 return replacementBuffer.toString();
94 }
95
96 public String getAdditionalLine() {
97 return null;
98 }
99 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 /**
30 * This class represents a conversion rule It uses a Pattern and defines for
31 * each capturing group of this Pattern a replacement text
32 *
33 * @author jean-noelcharpin
34 *
35 */
36 public class MultiGroupConversionRule implements ConversionRule {
37
38 // It is extremely unlikely to encounter more than 10 groups in one of
39 // our conversion reg-expressions
40 final private static int MAX_GROUPS = 10;
41
42 private Pattern pattern;
43 private String[] replacementTable = new String[MAX_GROUPS];
44
45 public MultiGroupConversionRule(Pattern pattern) {
46 this.pattern = pattern;
47 }
48
49 /*
50 * (non-Javadoc)
51 *
52 * @see org.slf4j.converter.ConversionRule#getPattern()
53 */
54 public Pattern getPattern() {
55 return pattern;
56 }
57
58 public void addReplacement(int groupIndex, String replacement) {
59 if (groupIndex == 0) {
60 throw new IllegalArgumentException("regex groups start at 1, not zero");
61 }
62 replacementTable[groupIndex] = replacement;
63 }
64
65 /*
66 * (non-Javadoc)
67 *
68 * @see org.slf4j.converter.ConversionRule#getReplacement(java.lang.Integer)
69 */
70 public String getReplacement(int groupIndex) {
71 return replacementTable[groupIndex];
72 }
73
74 /*
75 * (non-Javadoc)
76 *
77 * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher)
78 */
79 public String replace(Matcher matcher) {
80 StringBuilder replacementBuffer = new StringBuilder();
81 String replacementText;
82
83 for (int group = 1; group <= matcher.groupCount(); group++) {
84 replacementText = getReplacement(group);
85 if (replacementText != null) {
86 // System.out.println("replacing group " + group + " : "
87 // + matcher.group(group) + " with " + replacementText);
88 replacementBuffer.append(replacementText);
89 } else {
90 replacementBuffer.append(matcher.group(group));
91 }
92 }
93 return replacementBuffer.toString();
94 }
95
96 public String getAdditionalLine() {
97 return null;
98 }
99 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.Iterator;
27
28 public interface RuleSet {
29
30 Iterator<ConversionRule> iterator();
31
32 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.Iterator;
27
28 public interface RuleSet {
29
30 Iterator<ConversionRule> iterator();
31
32 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 /**
30 * This class represents a conversion rule It uses a Pattern and defines for
31 * each capturing group of this Pattern a replacement text
32 *
33 * @author jean-noelcharpin
34 *
35 */
36 public class SingleConversionRule implements ConversionRule {
37
38 final private Pattern pattern;
39 final private String replacementText;
40 final private String additionalLine;
41
42 public SingleConversionRule(Pattern pattern, String replacementText) {
43 this(pattern, replacementText, null);
44 }
45
46 public SingleConversionRule(Pattern pattern, String replacementText, String additionalLine) {
47 this.pattern = pattern;
48 this.replacementText = replacementText;
49 this.additionalLine = additionalLine;
50 }
51
52 /*
53 * (non-Javadoc)
54 *
55 * @see org.slf4j.converter.ConversionRule#getPattern()
56 */
57 public Pattern getPattern() {
58 return pattern;
59 }
60
61 /*
62 * (non-Javadoc)
63 *
64 * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher)
65 */
66 public String replace(Matcher matcher) {
67 return replacementText;
68 }
69
70 public String getAdditionalLine() {
71 return additionalLine;
72 }
73
74 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 /**
30 * This class represents a conversion rule It uses a Pattern and defines for
31 * each capturing group of this Pattern a replacement text
32 *
33 * @author jean-noelcharpin
34 *
35 */
36 public class SingleConversionRule implements ConversionRule {
37
38 final private Pattern pattern;
39 final private String replacementText;
40 final private String additionalLine;
41
42 public SingleConversionRule(Pattern pattern, String replacementText) {
43 this(pattern, replacementText, null);
44 }
45
46 public SingleConversionRule(Pattern pattern, String replacementText, String additionalLine) {
47 this.pattern = pattern;
48 this.replacementText = replacementText;
49 this.additionalLine = additionalLine;
50 }
51
52 /*
53 * (non-Javadoc)
54 *
55 * @see org.slf4j.converter.ConversionRule#getPattern()
56 */
57 public Pattern getPattern() {
58 return pattern;
59 }
60
61 /*
62 * (non-Javadoc)
63 *
64 * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher)
65 */
66 public String replace(Matcher matcher) {
67 return replacementText;
68 }
69
70 public String getAdditionalLine() {
71 return additionalLine;
72 }
73
74 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ org.slf4j.migrator.PackageTest.class, org.slf4j.migrator.line.PackageTest.class, org.slf4j.migrator.helper.PackageTest.class })
32 public class AllTest {
33
34 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ org.slf4j.migrator.PackageTest.class, org.slf4j.migrator.line.PackageTest.class, org.slf4j.migrator.helper.PackageTest.class })
32 public class AllTest {
33
34 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 import org.slf4j.migrator.line.MultiGroupConversionRule;
30
31 import junit.framework.TestCase;
32
33 public class AternativeApproach extends TestCase {
34
35 /**
36 * In this test we see that we cans use more simple Pattern to do the
37 * conversion
38 *
39 */
40 public void test() {
41 MultiGroupConversionRule cr2 = new MultiGroupConversionRule(Pattern.compile("(.*)(Log)"));
42 cr2.addReplacement(2, "LOGGER");
43
44 String s = "abcd Log";
45 Pattern pat = cr2.getPattern();
46 Matcher m = pat.matcher(s);
47
48 assertTrue(m.matches());
49 String r = cr2.replace(m);
50 assertEquals("abcd LOGGER", r);
51
52 System.out.println(r);
53 }
54
55 /**
56 * In this test we replace, using the simple Pattern (Log), the full Log
57 * declaration and instantiation. This is not convenient because we will also
58 * replace all String containing "Log".
59 */
60 public void test2() {
61 Pattern pat = Pattern.compile("(Log)");
62 String s = "abcd Log =";
63 Matcher m = pat.matcher(s);
64 assertTrue(m.find());
65 String r = m.replaceAll("Logger");
66 assertEquals("abcd Logger =", r);
67
68 String s1 = "Log l = LogFactory.getLog(MyClass.class);";
69 m = pat.matcher(s1);
70 assertTrue(m.find());
71 r = m.replaceAll("Logger");
72 assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", r);
73
74 String s2 = "Logabc ";
75 m = pat.matcher(s2);
76 assertTrue(m.find());
77
78 String s3 = "abcLog";
79 m = pat.matcher(s3);
80 assertTrue(m.find());
81 }
82
83 /**
84 * In this test we use a simple Pattern to replace the log instantiation
85 * without influence on Log declaration.
86 *
87 */
88 public void test3() {
89 Pattern pat = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\(");
90 String s = "Log log = LogFactory.getFactory().getInstance(\"x\");";
91 Matcher m = pat.matcher(s);
92 assertTrue(m.find());
93 String r = m.replaceAll("LoggerFactory.getLogger(");
94 assertEquals("Log log = LoggerFactory.getLogger(\"x\");", r);
95
96 String nonMatching = "Log log = xxx;";
97 pat.matcher(nonMatching);
98 assertFalse(m.find());
99 }
100
101 /**
102 * In this test we try to replace keyword Log without influence on String
103 * containing Log We see that we have to use two different Patterns
104 */
105 public void test4() {
106 Pattern pat = Pattern.compile("(\\sLog\\b)");
107 String s = "abcd Log =";
108 Matcher m = pat.matcher(s);
109 assertTrue(m.find());
110 String r = m.replaceAll(" Logger");
111 assertEquals("abcd Logger =", r);
112
113 String s2 = "Logabcd ";
114 m = pat.matcher(s2);
115 assertFalse(m.find());
116
117 String s3 = "abcdLogabcd ";
118 m = pat.matcher(s3);
119 assertFalse(m.find());
120
121 String s4 = "abcdLog";
122 m = pat.matcher(s4);
123 assertFalse(m.find());
124
125 String s5 = "Log myLog";
126 m = pat.matcher(s5);
127 assertFalse(m.find());
128
129 Pattern pat2 = Pattern.compile("^Log\\b");
130 Matcher m2 = pat2.matcher(s5);
131 assertTrue(m2.find());
132 r = m2.replaceAll("Logger");
133 assertEquals("Logger myLog", r);
134 }
135
136 /**
137 * In this test we combine two Pattern to achieve the intended conversion
138 */
139 public void test5() {
140 Pattern pat = Pattern.compile("(\\sLog\\b)");
141 String s = "public Log myLog =LogFactory.getFactory().getInstance(myClass.class);";
142 Matcher m = pat.matcher(s);
143 assertTrue(m.find());
144 String r = m.replaceAll(" Logger");
145 assertEquals("public Logger myLog =LogFactory.getFactory().getInstance(myClass.class);", r);
146
147 Pattern pat2 = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\(");
148 m = pat2.matcher(r);
149 assertTrue(m.find());
150 r = m.replaceAll("LoggerFactory.getLogger(");
151 assertEquals("public Logger myLog =LoggerFactory.getLogger(myClass.class);", r);
152 }
153 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 import org.slf4j.migrator.line.MultiGroupConversionRule;
30
31 import junit.framework.TestCase;
32
33 public class AternativeApproach extends TestCase {
34
35 /**
36 * In this test we see that we cans use more simple Pattern to do the
37 * conversion
38 *
39 */
40 public void test() {
41 MultiGroupConversionRule cr2 = new MultiGroupConversionRule(Pattern.compile("(.*)(Log)"));
42 cr2.addReplacement(2, "LOGGER");
43
44 String s = "abcd Log";
45 Pattern pat = cr2.getPattern();
46 Matcher m = pat.matcher(s);
47
48 assertTrue(m.matches());
49 String r = cr2.replace(m);
50 assertEquals("abcd LOGGER", r);
51
52 System.out.println(r);
53 }
54
55 /**
56 * In this test we replace, using the simple Pattern (Log), the full Log
57 * declaration and instantiation. This is not convenient because we will also
58 * replace all String containing "Log".
59 */
60 public void test2() {
61 Pattern pat = Pattern.compile("(Log)");
62 String s = "abcd Log =";
63 Matcher m = pat.matcher(s);
64 assertTrue(m.find());
65 String r = m.replaceAll("Logger");
66 assertEquals("abcd Logger =", r);
67
68 String s1 = "Log l = LogFactory.getLog(MyClass.class);";
69 m = pat.matcher(s1);
70 assertTrue(m.find());
71 r = m.replaceAll("Logger");
72 assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", r);
73
74 String s2 = "Logabc ";
75 m = pat.matcher(s2);
76 assertTrue(m.find());
77
78 String s3 = "abcLog";
79 m = pat.matcher(s3);
80 assertTrue(m.find());
81 }
82
83 /**
84 * In this test we use a simple Pattern to replace the log instantiation
85 * without influence on Log declaration.
86 *
87 */
88 public void test3() {
89 Pattern pat = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\(");
90 String s = "Log log = LogFactory.getFactory().getInstance(\"x\");";
91 Matcher m = pat.matcher(s);
92 assertTrue(m.find());
93 String r = m.replaceAll("LoggerFactory.getLogger(");
94 assertEquals("Log log = LoggerFactory.getLogger(\"x\");", r);
95
96 String nonMatching = "Log log = xxx;";
97 pat.matcher(nonMatching);
98 assertFalse(m.find());
99 }
100
101 /**
102 * In this test we try to replace keyword Log without influence on String
103 * containing Log We see that we have to use two different Patterns
104 */
105 public void test4() {
106 Pattern pat = Pattern.compile("(\\sLog\\b)");
107 String s = "abcd Log =";
108 Matcher m = pat.matcher(s);
109 assertTrue(m.find());
110 String r = m.replaceAll(" Logger");
111 assertEquals("abcd Logger =", r);
112
113 String s2 = "Logabcd ";
114 m = pat.matcher(s2);
115 assertFalse(m.find());
116
117 String s3 = "abcdLogabcd ";
118 m = pat.matcher(s3);
119 assertFalse(m.find());
120
121 String s4 = "abcdLog";
122 m = pat.matcher(s4);
123 assertFalse(m.find());
124
125 String s5 = "Log myLog";
126 m = pat.matcher(s5);
127 assertFalse(m.find());
128
129 Pattern pat2 = Pattern.compile("^Log\\b");
130 Matcher m2 = pat2.matcher(s5);
131 assertTrue(m2.find());
132 r = m2.replaceAll("Logger");
133 assertEquals("Logger myLog", r);
134 }
135
136 /**
137 * In this test we combine two Pattern to achieve the intended conversion
138 */
139 public void test5() {
140 Pattern pat = Pattern.compile("(\\sLog\\b)");
141 String s = "public Log myLog =LogFactory.getFactory().getInstance(myClass.class);";
142 Matcher m = pat.matcher(s);
143 assertTrue(m.find());
144 String r = m.replaceAll(" Logger");
145 assertEquals("public Logger myLog =LogFactory.getFactory().getInstance(myClass.class);", r);
146
147 Pattern pat2 = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\(");
148 m = pat2.matcher(r);
149 assertTrue(m.find());
150 r = m.replaceAll("LoggerFactory.getLogger(");
151 assertEquals("public Logger myLog =LoggerFactory.getLogger(myClass.class);", r);
152 }
153 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27 import java.io.IOException;
28
29 import org.junit.Ignore;
30 import org.junit.Test;
31 import org.slf4j.migrator.internal.NopProgressListener;
32 import org.slf4j.migrator.line.EmptyRuleSet;
33
34 public class FileConverterTest {
35
36 @Test
37 @Ignore
38 public void XtestNOP() throws IOException {
39 InplaceFileConverter fc = new InplaceFileConverter(new EmptyRuleSet(), new NopProgressListener());
40 fc.convert(new File("c:/varargs.txt"));
41 }
42 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27 import java.io.IOException;
28
29 import org.junit.Ignore;
30 import org.junit.Test;
31 import org.slf4j.migrator.internal.NopProgressListener;
32 import org.slf4j.migrator.line.EmptyRuleSet;
33
34 public class FileConverterTest {
35
36 @Test
37 @Ignore
38 public void XtestNOP() throws IOException {
39 InplaceFileConverter fc = new InplaceFileConverter(new EmptyRuleSet(), new NopProgressListener());
40 fc.convert(new File("c:/varargs.txt"));
41 }
42 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ AternativeApproach.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ AternativeApproach.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27
28 import org.junit.Ignore;
29 import org.junit.Test;
30 import org.slf4j.migrator.internal.NopProgressListener;
31
32 public class ProjectConverterTest {
33
34 public void test() {
35 }
36
37 @Test
38 @Ignore
39 public void XtestBarracuda() {
40 ProjectConverter pc = new ProjectConverter(Constant.LOG4J_TO_SLF4J, new NopProgressListener());
41 File projectFolder = new File("c:/home/ceki//Varia/Barracuda");
42 pc.convertProject(projectFolder);
43 }
44 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27
28 import org.junit.Ignore;
29 import org.junit.Test;
30 import org.slf4j.migrator.internal.NopProgressListener;
31
32 public class ProjectConverterTest {
33
34 public void test() {
35 }
36
37 @Test
38 @Ignore
39 public void XtestBarracuda() {
40 ProjectConverter pc = new ProjectConverter(Constant.LOG4J_TO_SLF4J, new NopProgressListener());
41 File projectFolder = new File("c:/home/ceki//Varia/Barracuda");
42 pc.convertProject(projectFolder);
43 }
44 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
28
29 import org.junit.Test;
30
31 public class AbbreviatorTest {
32
33 static final char FS = '/';
34 static final String INPUT_0 = "/abc/123456/ABC";
35 static final String INPUT_1 = "/abc/123456/xxxxx/ABC";
36
37 RandomHelper rh = new RandomHelper(FS);
38
39 @Test
40 public void testSmoke() {
41 {
42 Abbreviator abb = new Abbreviator(2, 100, FS);
43 String r = abb.abbreviate(INPUT_0);
44 assertEquals(INPUT_0, r);
45 }
46
47 {
48 Abbreviator abb = new Abbreviator(3, 8, FS);
49 String r = abb.abbreviate(INPUT_0);
50 assertEquals("/abc/.../ABC", r);
51 }
52 {
53 Abbreviator abb = new Abbreviator(3, 8, FS);
54 String r = abb.abbreviate(INPUT_0);
55 assertEquals("/abc/.../ABC", r);
56 }
57 }
58
59 @Test
60 public void testImpossibleToAbbreviate() {
61 Abbreviator abb = new Abbreviator(2, 20, FS);
62 String in = "iczldqwivpgm/mgrmvbjdxrwmqgprdjusth";
63 String r = abb.abbreviate(in);
64 assertEquals(in, r);
65 }
66
67 @Test
68 public void testNoFS() {
69 Abbreviator abb = new Abbreviator(2, 100, FS);
70 String r = abb.abbreviate("hello");
71 assertEquals("hello", r);
72
73 }
74
75 @Test
76 public void testZeroPrefix() {
77 {
78 Abbreviator abb = new Abbreviator(0, 100, FS);
79 String r = abb.abbreviate(INPUT_0);
80 assertEquals(INPUT_0, r);
81 }
82 }
83
84 @Test
85 public void testTheories() {
86 int MAX_RANDOM_FIXED_LEN = 20;
87 int MAX_RANDOM_AVG_LEN = 20;
88 int MAX_RANDOM_MAX_LEN = 100;
89 for (int i = 0; i < 10000; i++) {
90
91 // System.out.println("Test number " + i);
92
93 // 0 <= fixedLen < MAX_RANDOM_FIXED_LEN
94 int fixedLen = rh.nextInt(MAX_RANDOM_FIXED_LEN);
95 // 5 <= averageLen < MAX_RANDOM_AVG_LEN
96 int averageLen = rh.nextInt(MAX_RANDOM_AVG_LEN) + 3;
97 // System.out.println("fixedLen="+fixedLen+", averageLen="+averageLen);
98
99 int maxLen = rh.nextInt(MAX_RANDOM_MAX_LEN) + fixedLen;
100 if (maxLen <= 1) {
101 continue;
102 }
103 // System.out.println("maxLen="+maxLen);
104 int targetLen = (maxLen / 2) + rh.nextInt(maxLen / 2) + 1;
105
106 if (targetLen > maxLen) {
107 targetLen = maxLen;
108 }
109 String filename = rh.buildRandomFileName(averageLen, maxLen);
110
111 Abbreviator abb = new Abbreviator(fixedLen, targetLen, FS);
112 String result = abb.abbreviate(filename);
113 assertTheory0(averageLen, filename, result, fixedLen, targetLen);
114 assertUsefulness(averageLen, filename, result, fixedLen, targetLen);
115 assertTheory1(filename, result, fixedLen, targetLen);
116 assertTheory2(filename, result, fixedLen, targetLen);
117 }
118 }
119
120 // result length is smaller than original length
121 void assertTheory0(int averageLen, String filename, String result, int fixedLen, int targetLength) {
122 assertTrue("filename=[" + filename + "] result=[" + result + "]", result.length() <= filename.length());
123 }
124
125 // if conditions allow, result length should be to target length
126 void assertUsefulness(int averageLen, String filename, String result, int fixedLen, int targetLength) {
127 int resLen = result.length();
128
129 int margin = averageLen * 4;
130 if (targetLength > fixedLen + margin) {
131 assertTrue("filename=[" + filename + "], result=[" + result + "] resultLength=" + resLen + " fixedLength=" + fixedLen + ", targetLength="
132 + targetLength + ", avgLen=" + averageLen, result.length() <= targetLength + averageLen);
133 }
134 }
135
136 // result start with prefix found in filename
137 void assertTheory1(String filename, String result, int fixedLen, int targetLength) {
138 String prefix = filename.substring(0, fixedLen);
139 assertTrue(result.startsWith(prefix));
140 }
141
142 // The string /.../ is found in the result once at a position higher
143 // than fixedLen
144 void assertTheory2(String filename, String result, int fixedLen, int targetLength) {
145 if (filename == result) {
146 return;
147 }
148 int fillerIndex = result.indexOf(Abbreviator.FILLER);
149 assertTrue(fillerIndex >= fixedLen);
150 }
151 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
28
29 import org.junit.Test;
30
31 public class AbbreviatorTest {
32
33 static final char FS = '/';
34 static final String INPUT_0 = "/abc/123456/ABC";
35 static final String INPUT_1 = "/abc/123456/xxxxx/ABC";
36
37 RandomHelper rh = new RandomHelper(FS);
38
39 @Test
40 public void testSmoke() {
41 {
42 Abbreviator abb = new Abbreviator(2, 100, FS);
43 String r = abb.abbreviate(INPUT_0);
44 assertEquals(INPUT_0, r);
45 }
46
47 {
48 Abbreviator abb = new Abbreviator(3, 8, FS);
49 String r = abb.abbreviate(INPUT_0);
50 assertEquals("/abc/.../ABC", r);
51 }
52 {
53 Abbreviator abb = new Abbreviator(3, 8, FS);
54 String r = abb.abbreviate(INPUT_0);
55 assertEquals("/abc/.../ABC", r);
56 }
57 }
58
59 @Test
60 public void testImpossibleToAbbreviate() {
61 Abbreviator abb = new Abbreviator(2, 20, FS);
62 String in = "iczldqwivpgm/mgrmvbjdxrwmqgprdjusth";
63 String r = abb.abbreviate(in);
64 assertEquals(in, r);
65 }
66
67 @Test
68 public void testNoFS() {
69 Abbreviator abb = new Abbreviator(2, 100, FS);
70 String r = abb.abbreviate("hello");
71 assertEquals("hello", r);
72
73 }
74
75 @Test
76 public void testZeroPrefix() {
77 {
78 Abbreviator abb = new Abbreviator(0, 100, FS);
79 String r = abb.abbreviate(INPUT_0);
80 assertEquals(INPUT_0, r);
81 }
82 }
83
84 @Test
85 public void testTheories() {
86 int MAX_RANDOM_FIXED_LEN = 20;
87 int MAX_RANDOM_AVG_LEN = 20;
88 int MAX_RANDOM_MAX_LEN = 100;
89 for (int i = 0; i < 10000; i++) {
90
91 // System.out.println("Test number " + i);
92
93 // 0 <= fixedLen < MAX_RANDOM_FIXED_LEN
94 int fixedLen = rh.nextInt(MAX_RANDOM_FIXED_LEN);
95 // 5 <= averageLen < MAX_RANDOM_AVG_LEN
96 int averageLen = rh.nextInt(MAX_RANDOM_AVG_LEN) + 3;
97 // System.out.println("fixedLen="+fixedLen+", averageLen="+averageLen);
98
99 int maxLen = rh.nextInt(MAX_RANDOM_MAX_LEN) + fixedLen;
100 if (maxLen <= 1) {
101 continue;
102 }
103 // System.out.println("maxLen="+maxLen);
104 int targetLen = (maxLen / 2) + rh.nextInt(maxLen / 2) + 1;
105
106 if (targetLen > maxLen) {
107 targetLen = maxLen;
108 }
109 String filename = rh.buildRandomFileName(averageLen, maxLen);
110
111 Abbreviator abb = new Abbreviator(fixedLen, targetLen, FS);
112 String result = abb.abbreviate(filename);
113 assertTheory0(averageLen, filename, result, fixedLen, targetLen);
114 assertUsefulness(averageLen, filename, result, fixedLen, targetLen);
115 assertTheory1(filename, result, fixedLen, targetLen);
116 assertTheory2(filename, result, fixedLen, targetLen);
117 }
118 }
119
120 // result length is smaller than original length
121 void assertTheory0(int averageLen, String filename, String result, int fixedLen, int targetLength) {
122 assertTrue("filename=[" + filename + "] result=[" + result + "]", result.length() <= filename.length());
123 }
124
125 // if conditions allow, result length should be to target length
126 void assertUsefulness(int averageLen, String filename, String result, int fixedLen, int targetLength) {
127 int resLen = result.length();
128
129 int margin = averageLen * 4;
130 if (targetLength > fixedLen + margin) {
131 assertTrue("filename=[" + filename + "], result=[" + result + "] resultLength=" + resLen + " fixedLength=" + fixedLen + ", targetLength="
132 + targetLength + ", avgLen=" + averageLen, result.length() <= targetLength + averageLen);
133 }
134 }
135
136 // result start with prefix found in filename
137 void assertTheory1(String filename, String result, int fixedLen, int targetLength) {
138 String prefix = filename.substring(0, fixedLen);
139 assertTrue(result.startsWith(prefix));
140 }
141
142 // The string /.../ is found in the result once at a position higher
143 // than fixedLen
144 void assertTheory2(String filename, String result, int fixedLen, int targetLength) {
145 if (filename == result) {
146 return;
147 }
148 int fillerIndex = result.indexOf(Abbreviator.FILLER);
149 assertTrue(fillerIndex >= fixedLen);
150 }
151 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ AbbreviatorTest.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ AbbreviatorTest.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import java.util.Random;
27
28 public class RandomHelper {
29
30 private Random random = new Random(100);
31 final char folderSeparator;
32
33 RandomHelper(char folderSeparator) {
34 this.folderSeparator = folderSeparator;
35 }
36
37 private String randomString(int len) {
38 StringBuilder buf = new StringBuilder();
39 for (int i = 0; i < len; i++) {
40 int offset = random.nextInt(26);
41 char c = (char) ('a' + offset);
42 buf.append(c);
43 }
44 return buf.toString();
45 }
46
47 int nextInt(int n) {
48 return random.nextInt(n);
49 }
50
51 String buildRandomFileName(int averageNodeLength, int totalLength) {
52 StringBuilder buf = new StringBuilder();
53 int MAX_NODE_LENGTH = averageNodeLength * 2;
54 while (buf.length() < totalLength) {
55 int remaining = totalLength - buf.length();
56 int currentNodeLength;
57 if (remaining > MAX_NODE_LENGTH) {
58 currentNodeLength = random.nextInt(MAX_NODE_LENGTH) + 1;
59 buf.append(randomString(currentNodeLength));
60 buf.append('/');
61 } else {
62 currentNodeLength = remaining;
63 buf.append(randomString(currentNodeLength));
64 }
65 }
66 return buf.toString();
67 }
68
69 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import java.util.Random;
27
28 public class RandomHelper {
29
30 private Random random = new Random(100);
31 final char folderSeparator;
32
33 RandomHelper(char folderSeparator) {
34 this.folderSeparator = folderSeparator;
35 }
36
37 private String randomString(int len) {
38 StringBuilder buf = new StringBuilder();
39 for (int i = 0; i < len; i++) {
40 int offset = random.nextInt(26);
41 char c = (char) ('a' + offset);
42 buf.append(c);
43 }
44 return buf.toString();
45 }
46
47 int nextInt(int n) {
48 return random.nextInt(n);
49 }
50
51 String buildRandomFileName(int averageNodeLength, int totalLength) {
52 StringBuilder buf = new StringBuilder();
53 int MAX_NODE_LENGTH = averageNodeLength * 2;
54 while (buf.length() < totalLength) {
55 int remaining = totalLength - buf.length();
56 int currentNodeLength;
57 if (remaining > MAX_NODE_LENGTH) {
58 currentNodeLength = random.nextInt(MAX_NODE_LENGTH) + 1;
59 buf.append(randomString(currentNodeLength));
60 buf.append('/');
61 } else {
62 currentNodeLength = remaining;
63 buf.append(randomString(currentNodeLength));
64 }
65 }
66 return buf.toString();
67 }
68
69 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27
28 import org.slf4j.migrator.internal.ProgressListener;
29
30 public class NopProgressListener implements ProgressListener {
31
32 public void onDirectory(File file) {
33 }
34
35 public void onDone() {
36 }
37
38 public void onFileAddition(File file) {
39 }
40
41 public void onFileScan(File file) {
42 }
43
44 public void onInplaceConversion(File file) {
45 }
46
47 public void onFileScanBegin() {
48 }
49
50 public void onMigrationBegin() {
51 }
52
53 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27
28 import org.slf4j.migrator.internal.ProgressListener;
29
30 public class NopProgressListener implements ProgressListener {
31
32 public void onDirectory(File file) {
33 }
34
35 public void onDone() {
36 }
37
38 public void onFileAddition(File file) {
39 }
40
41 public void onFileScan(File file) {
42 }
43
44 public void onInplaceConversion(File file) {
45 }
46
47 public void onFileScanBegin() {
48 }
49
50 public void onMigrationBegin() {
51 }
52
53 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29
30 public class JCLRuleSetTest {
31
32 LineConverter jclConverter = new LineConverter(new JCLRuleSet());
33
34 @Test
35 public void testImportReplacement() {
36 // LogFactory import replacement
37 assertEquals("import org.slf4j.LoggerFactory;", jclConverter.getOneLineReplacement("import org.apache.commons.logging.LogFactory;"));
38 // Log import replacement
39 assertEquals("import org.slf4j.Logger;", jclConverter.getOneLineReplacement("import org.apache.commons.logging.Log;"));
40 }
41
42 @Test
43 public void testLogFactoryGetLogReplacement() {
44 // Logger declaration and instanciation without modifier
45 assertEquals(" Logger l = LoggerFactory.getLogger(MyClass.class);",
46 jclConverter.getOneLineReplacement(" Log l = LogFactory.getLog(MyClass.class);"));
47 // Logger declaration and instanciation with one modifier
48 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
49 jclConverter.getOneLineReplacement("public Log mylog=LogFactory.getLog(MyClass.class);"));
50 // Logger declaration and instanciation with two modifier
51 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
52 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class);"));
53 // Logger declaration and instanciation with two modifier and comment at the
54 // end of line
55 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); //logger instanciation and declaration",
56 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class); //logger instanciation and declaration"));
57 // Logger instanciation without declaration and comment at the end of line
58 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
59 jclConverter.getOneLineReplacement(" myLog = LogFactory.getLog(MyClass.class);//logger instanciation"));
60 // commented Logger declaration and instanciation with two modifier
61 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
62 jclConverter.getOneLineReplacement("//public static Log mylog1 = LogFactory.getLog(MyClass.class);"));
63 // commented Logger instanciation without declaration
64 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
65 jclConverter.getOneLineReplacement("// myLog = LogFactory.getLog(MyClass.class);//logger instanciation"));
66 }
67
68 @Test
69 public void testLogFactoryGetFactoryReplacement() {
70
71 // Logger declaration and instanciation without modifier
72 assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);",
73 jclConverter.getOneLineReplacement("Log l = LogFactory.getFactory().getInstance(MyClass.class);"));
74 // Logger declaration and instanciation with one modifier
75 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
76 jclConverter.getOneLineReplacement("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);"));
77 // Logger declaration and instanciation with modifiers
78 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
79 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class);"));
80 // Logger declaration and instanciation with two modifier and comment at the
81 // end of line
82 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); //logger instanciation and declaration",
83 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class); //logger instanciation and declaration"));
84 // Logger instanciation without declaration and comment at the end of line
85 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
86 jclConverter.getOneLineReplacement(" myLog = LogFactory.getFactory().getInstance(MyClass.class);//logger instanciation"));
87 // commented Logger declaration and instanciation with two modifier
88 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
89 jclConverter.getOneLineReplacement("//public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class);"));
90 // commented Logger instanciation without declaration
91 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
92 jclConverter.getOneLineReplacement("// myLog = LogFactory.getFactory().getInstance(MyClass.class);//logger instanciation"));
93 }
94
95 @Test
96 public void testLogDeclarationReplacement() {
97
98 // simple Logger declaration
99 assertEquals("Logger mylog;", jclConverter.getOneLineReplacement("Log mylog;"));
100 // Logger declaration with a modifier
101 assertEquals("private Logger mylog;", jclConverter.getOneLineReplacement("private Log mylog;"));
102
103 // Logger declaration with modifiers
104 assertEquals("public static final Logger myLog;", jclConverter.getOneLineReplacement("public static final Log myLog;"));
105 // Logger declaration with modifiers and comment at the end of line
106 assertEquals("public Logger myLog;//logger declaration", jclConverter.getOneLineReplacement("public Log myLog;//logger declaration"));
107 // commented Logger declaration
108 assertEquals("//private Logger myLog;", jclConverter.getOneLineReplacement("//private Log myLog;"));
109 }
110
111 @Test
112 public void testMultiLineReplacement() {
113 // Logger declaration on a line
114 assertEquals("protected Logger log =", jclConverter.getOneLineReplacement("protected Log log ="));
115
116 // Logger instanciation on the next line
117 assertEquals(" LoggerFactory.getLogger(MyComponent.class);", jclConverter.getOneLineReplacement(" LogFactory.getLog(MyComponent.class);"));
118 // Logger declaration on a line
119 assertEquals("protected Logger log ", jclConverter.getOneLineReplacement("protected Log log "));
120 // Logger instanciation on the next line
121 assertEquals(" = LoggerFactory.getLogger(MyComponent.class);",
122 jclConverter.getOneLineReplacement(" = LogFactory.getFactory().getInstance(MyComponent.class);"));
123 }
124 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29
30 public class JCLRuleSetTest {
31
32 LineConverter jclConverter = new LineConverter(new JCLRuleSet());
33
34 @Test
35 public void testImportReplacement() {
36 // LogFactory import replacement
37 assertEquals("import org.slf4j.LoggerFactory;", jclConverter.getOneLineReplacement("import org.apache.commons.logging.LogFactory;"));
38 // Log import replacement
39 assertEquals("import org.slf4j.Logger;", jclConverter.getOneLineReplacement("import org.apache.commons.logging.Log;"));
40 }
41
42 @Test
43 public void testLogFactoryGetLogReplacement() {
44 // Logger declaration and instanciation without modifier
45 assertEquals(" Logger l = LoggerFactory.getLogger(MyClass.class);",
46 jclConverter.getOneLineReplacement(" Log l = LogFactory.getLog(MyClass.class);"));
47 // Logger declaration and instanciation with one modifier
48 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
49 jclConverter.getOneLineReplacement("public Log mylog=LogFactory.getLog(MyClass.class);"));
50 // Logger declaration and instanciation with two modifier
51 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
52 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class);"));
53 // Logger declaration and instanciation with two modifier and comment at the
54 // end of line
55 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); //logger instanciation and declaration",
56 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class); //logger instanciation and declaration"));
57 // Logger instanciation without declaration and comment at the end of line
58 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
59 jclConverter.getOneLineReplacement(" myLog = LogFactory.getLog(MyClass.class);//logger instanciation"));
60 // commented Logger declaration and instanciation with two modifier
61 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
62 jclConverter.getOneLineReplacement("//public static Log mylog1 = LogFactory.getLog(MyClass.class);"));
63 // commented Logger instanciation without declaration
64 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
65 jclConverter.getOneLineReplacement("// myLog = LogFactory.getLog(MyClass.class);//logger instanciation"));
66 }
67
68 @Test
69 public void testLogFactoryGetFactoryReplacement() {
70
71 // Logger declaration and instanciation without modifier
72 assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);",
73 jclConverter.getOneLineReplacement("Log l = LogFactory.getFactory().getInstance(MyClass.class);"));
74 // Logger declaration and instanciation with one modifier
75 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
76 jclConverter.getOneLineReplacement("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);"));
77 // Logger declaration and instanciation with modifiers
78 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
79 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class);"));
80 // Logger declaration and instanciation with two modifier and comment at the
81 // end of line
82 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); //logger instanciation and declaration",
83 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class); //logger instanciation and declaration"));
84 // Logger instanciation without declaration and comment at the end of line
85 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
86 jclConverter.getOneLineReplacement(" myLog = LogFactory.getFactory().getInstance(MyClass.class);//logger instanciation"));
87 // commented Logger declaration and instanciation with two modifier
88 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
89 jclConverter.getOneLineReplacement("//public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class);"));
90 // commented Logger instanciation without declaration
91 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
92 jclConverter.getOneLineReplacement("// myLog = LogFactory.getFactory().getInstance(MyClass.class);//logger instanciation"));
93 }
94
95 @Test
96 public void testLogDeclarationReplacement() {
97
98 // simple Logger declaration
99 assertEquals("Logger mylog;", jclConverter.getOneLineReplacement("Log mylog;"));
100 // Logger declaration with a modifier
101 assertEquals("private Logger mylog;", jclConverter.getOneLineReplacement("private Log mylog;"));
102
103 // Logger declaration with modifiers
104 assertEquals("public static final Logger myLog;", jclConverter.getOneLineReplacement("public static final Log myLog;"));
105 // Logger declaration with modifiers and comment at the end of line
106 assertEquals("public Logger myLog;//logger declaration", jclConverter.getOneLineReplacement("public Log myLog;//logger declaration"));
107 // commented Logger declaration
108 assertEquals("//private Logger myLog;", jclConverter.getOneLineReplacement("//private Log myLog;"));
109 }
110
111 @Test
112 public void testMultiLineReplacement() {
113 // Logger declaration on a line
114 assertEquals("protected Logger log =", jclConverter.getOneLineReplacement("protected Log log ="));
115
116 // Logger instanciation on the next line
117 assertEquals(" LoggerFactory.getLogger(MyComponent.class);", jclConverter.getOneLineReplacement(" LogFactory.getLog(MyComponent.class);"));
118 // Logger declaration on a line
119 assertEquals("protected Logger log ", jclConverter.getOneLineReplacement("protected Log log "));
120 // Logger instanciation on the next line
121 assertEquals(" = LoggerFactory.getLogger(MyComponent.class);",
122 jclConverter.getOneLineReplacement(" = LogFactory.getFactory().getInstance(MyComponent.class);"));
123 }
124 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.Arrays;
27
28 import org.junit.Test;
29 import org.slf4j.migrator.line.LineConverter;
30 import org.slf4j.migrator.line.Log4jRuleSet;
31
32 import static org.junit.Assert.assertEquals;
33 import static org.junit.Assert.assertTrue;
34
35 public class Log4jRuleSetTest {
36
37 LineConverter log4jConverter = new LineConverter(new Log4jRuleSet());
38
39 @Test
40 public void testImportReplacement() {
41 // LogFactory import replacement
42 assertEquals("import org.slf4j.LoggerFactory;", log4jConverter.getOneLineReplacement("import org.apache.log4j.LogManager;"));
43 // Log import replacement
44 assertTrue(Arrays.equals(new String[] { "import org.slf4j.Logger;", "import org.slf4j.LoggerFactory;" },
45 log4jConverter.getReplacement("import org.apache.log4j.Logger;")));
46 }
47
48 @Test
49 public void testLogManagerGetLoggerReplacement() {
50 // Logger declaration and instanciation without modifier
51 assertEquals(" Logger l = LoggerFactory.getLogger(MyClass.class);",
52 log4jConverter.getOneLineReplacement(" Logger l = LogManager.getLogger(MyClass.class);"));
53 // Logger declaration and instanciation with one modifier
54 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
55 log4jConverter.getOneLineReplacement("public Logger mylog=LogManager.getLogger(MyClass.class);"));
56 // Logger declaration and instanciation with two modifier
57 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
58 log4jConverter.getOneLineReplacement("public static Logger mylog1 = LogManager.getLogger(MyClass.class);"));
59 // Logger declaration and instanciation with two modifier and comment at the
60 // end of line
61 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);//logger instanciation and declaration",
62 log4jConverter.getOneLineReplacement("public static Logger mylog1 = LogManager.getLogger(MyClass.class);//logger instanciation and declaration"));
63 // Logger instanciation without declaration and comment at the end of line
64 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
65 log4jConverter.getOneLineReplacement(" myLog = LogManager.getLogger(MyClass.class);//logger instanciation"));
66 // commented Logger declaration and instanciation with two modifier
67 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
68 log4jConverter.getOneLineReplacement("//public static Logger mylog1 = LogManager.getLogger(MyClass.class);"));
69 // commented Logger instanciation without declaration
70 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
71 log4jConverter.getOneLineReplacement("// myLog = LogManager.getLogger(MyClass.class);//logger instanciation"));
72 }
73
74 @Test
75 public void testLoggerGetLoggerReplacement() {
76 // Logger declaration and instanciation without modifier
77 assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", log4jConverter.getOneLineReplacement("Logger l = Logger.getLogger(MyClass.class);"));
78 // Logger declaration and instanciation with one modifier
79 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
80 log4jConverter.getOneLineReplacement("public Logger mylog=Logger.getLogger(MyClass.class);"));
81 // Logger declaration and instanciation with modifiers
82 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
83 log4jConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class);"));
84 // Logger declaration and instanciation with two modifier and comment at the
85 // end of line
86 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); // logger instanciation and declaration",
87 log4jConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class); // logger instanciation and declaration"));
88 // Logger instanciation without declaration and comment at the end of line
89 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
90 log4jConverter.getOneLineReplacement(" myLog = Logger.getLogger(MyClass.class);//logger instanciation"));
91 // commented Logger declaration and instanciation with two modifier
92 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
93 log4jConverter.getOneLineReplacement("//public static Logger mylog1 = Logger.getLogger(MyClass.class);"));
94 // commented Logger instanciation without declaration
95 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
96 log4jConverter.getOneLineReplacement("// myLog = Logger.getLogger(MyClass.class);//logger instanciation"));
97 }
98
99 @Test
100 public void testLogDeclarationReplacement() {
101 // simple Logger declaration
102 assertEquals("Logger mylog;", log4jConverter.getOneLineReplacement("Logger mylog;"));
103 // Logger declaration with a modifier
104 assertEquals("private Logger mylog;", log4jConverter.getOneLineReplacement("private Logger mylog;"));
105
106 // Logger declaration with modifiers
107 assertEquals("public static final Logger myLog;", log4jConverter.getOneLineReplacement("public static final Logger myLog;"));
108 // Logger declaration with modifiers and comment at the end of line
109 assertEquals("public Logger myLog;//logger declaration", log4jConverter.getOneLineReplacement("public Logger myLog;//logger declaration"));
110 // commented Logger declaration
111 assertEquals("//private Logger myLog;", log4jConverter.getOneLineReplacement("//private Logger myLog;"));
112 }
113
114 @Test
115 public void testMultiLineReplacement() {
116 // Logger declaration on a line
117 assertEquals("protected Logger log =", log4jConverter.getOneLineReplacement("protected Logger log ="));
118
119 // Logger instanciation on the next line
120 assertEquals(" LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" LogManager.getLogger(MyComponent.class);"));
121 // Logger declaration on a line
122 assertEquals("protected Logger log ", log4jConverter.getOneLineReplacement("protected Logger log "));
123 // Logger instanciation on the next line
124 assertEquals(" = LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" = LogManager.getLogger(MyComponent.class);"));
125 }
126
127 @Test
128 public void categoryReplacement() {
129 // Category declaration on a line
130 assertEquals("protected Logger cat =", log4jConverter.getOneLineReplacement("protected Category cat ="));
131
132 assertEquals(" LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" Category.getInstance(MyComponent.class);"));
133 }
134
135 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.Arrays;
27
28 import org.junit.Test;
29 import org.slf4j.migrator.line.LineConverter;
30 import org.slf4j.migrator.line.Log4jRuleSet;
31
32 import static org.junit.Assert.assertEquals;
33 import static org.junit.Assert.assertTrue;
34
35 public class Log4jRuleSetTest {
36
37 LineConverter log4jConverter = new LineConverter(new Log4jRuleSet());
38
39 @Test
40 public void testImportReplacement() {
41 // LogFactory import replacement
42 assertEquals("import org.slf4j.LoggerFactory;", log4jConverter.getOneLineReplacement("import org.apache.log4j.LogManager;"));
43 // Log import replacement
44 assertTrue(Arrays.equals(new String[] { "import org.slf4j.Logger;", "import org.slf4j.LoggerFactory;" },
45 log4jConverter.getReplacement("import org.apache.log4j.Logger;")));
46 }
47
48 @Test
49 public void testLogManagerGetLoggerReplacement() {
50 // Logger declaration and instanciation without modifier
51 assertEquals(" Logger l = LoggerFactory.getLogger(MyClass.class);",
52 log4jConverter.getOneLineReplacement(" Logger l = LogManager.getLogger(MyClass.class);"));
53 // Logger declaration and instanciation with one modifier
54 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
55 log4jConverter.getOneLineReplacement("public Logger mylog=LogManager.getLogger(MyClass.class);"));
56 // Logger declaration and instanciation with two modifier
57 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
58 log4jConverter.getOneLineReplacement("public static Logger mylog1 = LogManager.getLogger(MyClass.class);"));
59 // Logger declaration and instanciation with two modifier and comment at the
60 // end of line
61 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);//logger instanciation and declaration",
62 log4jConverter.getOneLineReplacement("public static Logger mylog1 = LogManager.getLogger(MyClass.class);//logger instanciation and declaration"));
63 // Logger instanciation without declaration and comment at the end of line
64 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
65 log4jConverter.getOneLineReplacement(" myLog = LogManager.getLogger(MyClass.class);//logger instanciation"));
66 // commented Logger declaration and instanciation with two modifier
67 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
68 log4jConverter.getOneLineReplacement("//public static Logger mylog1 = LogManager.getLogger(MyClass.class);"));
69 // commented Logger instanciation without declaration
70 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
71 log4jConverter.getOneLineReplacement("// myLog = LogManager.getLogger(MyClass.class);//logger instanciation"));
72 }
73
74 @Test
75 public void testLoggerGetLoggerReplacement() {
76 // Logger declaration and instanciation without modifier
77 assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", log4jConverter.getOneLineReplacement("Logger l = Logger.getLogger(MyClass.class);"));
78 // Logger declaration and instanciation with one modifier
79 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
80 log4jConverter.getOneLineReplacement("public Logger mylog=Logger.getLogger(MyClass.class);"));
81 // Logger declaration and instanciation with modifiers
82 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
83 log4jConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class);"));
84 // Logger declaration and instanciation with two modifier and comment at the
85 // end of line
86 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); // logger instanciation and declaration",
87 log4jConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class); // logger instanciation and declaration"));
88 // Logger instanciation without declaration and comment at the end of line
89 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
90 log4jConverter.getOneLineReplacement(" myLog = Logger.getLogger(MyClass.class);//logger instanciation"));
91 // commented Logger declaration and instanciation with two modifier
92 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
93 log4jConverter.getOneLineReplacement("//public static Logger mylog1 = Logger.getLogger(MyClass.class);"));
94 // commented Logger instanciation without declaration
95 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
96 log4jConverter.getOneLineReplacement("// myLog = Logger.getLogger(MyClass.class);//logger instanciation"));
97 }
98
99 @Test
100 public void testLogDeclarationReplacement() {
101 // simple Logger declaration
102 assertEquals("Logger mylog;", log4jConverter.getOneLineReplacement("Logger mylog;"));
103 // Logger declaration with a modifier
104 assertEquals("private Logger mylog;", log4jConverter.getOneLineReplacement("private Logger mylog;"));
105
106 // Logger declaration with modifiers
107 assertEquals("public static final Logger myLog;", log4jConverter.getOneLineReplacement("public static final Logger myLog;"));
108 // Logger declaration with modifiers and comment at the end of line
109 assertEquals("public Logger myLog;//logger declaration", log4jConverter.getOneLineReplacement("public Logger myLog;//logger declaration"));
110 // commented Logger declaration
111 assertEquals("//private Logger myLog;", log4jConverter.getOneLineReplacement("//private Logger myLog;"));
112 }
113
114 @Test
115 public void testMultiLineReplacement() {
116 // Logger declaration on a line
117 assertEquals("protected Logger log =", log4jConverter.getOneLineReplacement("protected Logger log ="));
118
119 // Logger instanciation on the next line
120 assertEquals(" LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" LogManager.getLogger(MyComponent.class);"));
121 // Logger declaration on a line
122 assertEquals("protected Logger log ", log4jConverter.getOneLineReplacement("protected Logger log "));
123 // Logger instanciation on the next line
124 assertEquals(" = LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" = LogManager.getLogger(MyComponent.class);"));
125 }
126
127 @Test
128 public void categoryReplacement() {
129 // Category declaration on a line
130 assertEquals("protected Logger cat =", log4jConverter.getOneLineReplacement("protected Category cat ="));
131
132 assertEquals(" LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" Category.getInstance(MyComponent.class);"));
133 }
134
135 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29
30 public class NoConversionTest {
31
32 /**
33 * This test shows that performing JCL to SLF4J conversion has no impact on
34 * Log4j implementation
35 */
36 @Test
37 public void testJclOverLog4jConversion() {
38 // running jcl to slf4j conversion
39 // JCLMatcher jclMatcher =
40 LineConverter jclLineConverter = new LineConverter(new JCLRuleSet());
41 // no changes on log4j.LogManager import
42 assertEquals("import org.apache.log4j.LogManager;", jclLineConverter.getOneLineReplacement("import org.apache.log4j.LogManager;"));
43 // no changes on log4j.Logger import
44 assertEquals("import org.apache.log4j.Logger;", jclLineConverter.getOneLineReplacement("import org.apache.log4j.Logger;"));
45 // no changes on Logger instanciation using LogManager
46 assertEquals("Logger log = LogManager.getLogger(MyClass.class);",
47 jclLineConverter.getOneLineReplacement("Logger log = LogManager.getLogger(MyClass.class);"));
48 // no changes on Logger instanciation using Logger.getLogger
49 assertEquals("public static Logger mylog1 = Logger.getLogger(MyClass.class);",
50 jclLineConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class);"));
51 }
52
53 /**
54 * This test shows that performing Log4j to SLF4J conversion has no impact on
55 * JCL implementation
56 */
57 @Test
58 public void testLog4jOverJclConversion() {
59 // running log4j to slf4j conversion
60 LineConverter log4jConverter = new LineConverter(new Log4jRuleSet());
61
62 // no changes on LogFactory import
63 assertEquals("import org.apache.commons.logging.LogFactory;", log4jConverter.getOneLineReplacement("import org.apache.commons.logging.LogFactory;"));
64 // no changes on Log import
65 assertEquals("import org.apache.commons.logging.Log;", log4jConverter.getOneLineReplacement("import org.apache.commons.logging.Log;"));
66 // no changes on Log instanciation using Logfactory.getLog
67 assertEquals("public static Log mylog1 = LogFactory.getLog(MyClass.class);",
68 log4jConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class);"));
69 // no changes on log instanciation using LogFactory.getFactory().getInstance
70 assertEquals("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);",
71 log4jConverter.getOneLineReplacement("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);"));
72
73 }
74 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29
30 public class NoConversionTest {
31
32 /**
33 * This test shows that performing JCL to SLF4J conversion has no impact on
34 * Log4j implementation
35 */
36 @Test
37 public void testJclOverLog4jConversion() {
38 // running jcl to slf4j conversion
39 // JCLMatcher jclMatcher =
40 LineConverter jclLineConverter = new LineConverter(new JCLRuleSet());
41 // no changes on log4j.LogManager import
42 assertEquals("import org.apache.log4j.LogManager;", jclLineConverter.getOneLineReplacement("import org.apache.log4j.LogManager;"));
43 // no changes on log4j.Logger import
44 assertEquals("import org.apache.log4j.Logger;", jclLineConverter.getOneLineReplacement("import org.apache.log4j.Logger;"));
45 // no changes on Logger instanciation using LogManager
46 assertEquals("Logger log = LogManager.getLogger(MyClass.class);",
47 jclLineConverter.getOneLineReplacement("Logger log = LogManager.getLogger(MyClass.class);"));
48 // no changes on Logger instanciation using Logger.getLogger
49 assertEquals("public static Logger mylog1 = Logger.getLogger(MyClass.class);",
50 jclLineConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class);"));
51 }
52
53 /**
54 * This test shows that performing Log4j to SLF4J conversion has no impact on
55 * JCL implementation
56 */
57 @Test
58 public void testLog4jOverJclConversion() {
59 // running log4j to slf4j conversion
60 LineConverter log4jConverter = new LineConverter(new Log4jRuleSet());
61
62 // no changes on LogFactory import
63 assertEquals("import org.apache.commons.logging.LogFactory;", log4jConverter.getOneLineReplacement("import org.apache.commons.logging.LogFactory;"));
64 // no changes on Log import
65 assertEquals("import org.apache.commons.logging.Log;", log4jConverter.getOneLineReplacement("import org.apache.commons.logging.Log;"));
66 // no changes on Log instanciation using Logfactory.getLog
67 assertEquals("public static Log mylog1 = LogFactory.getLog(MyClass.class);",
68 log4jConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class);"));
69 // no changes on log instanciation using LogFactory.getFactory().getInstance
70 assertEquals("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);",
71 log4jConverter.getOneLineReplacement("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);"));
72
73 }
74 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ TrivialMatcherTest.class, JCLRuleSetTest.class, Log4jRuleSetTest.class, NoConversionTest.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ TrivialMatcherTest.class, JCLRuleSetTest.class, Log4jRuleSetTest.class, NoConversionTest.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 import org.slf4j.migrator.line.ConversionRule;
31 import org.slf4j.migrator.line.MultiGroupConversionRule;
32 import org.slf4j.migrator.line.RuleSet;
33 import org.slf4j.migrator.line.SingleConversionRule;
34
35 class TrivialMatcher implements RuleSet {
36
37 private ArrayList<ConversionRule> conversionRuleList;
38
39 public TrivialMatcher() {
40 // simple rule no capturing group is defined, we use default capturing group which is group zero
41 SingleConversionRule cr = new SingleConversionRule(Pattern.compile("import org.slf4j.converter"), "simple replacement with an unique capturing group");
42
43 // we define 4 differents capturing groups
44 MultiGroupConversionRule cr1 = new MultiGroupConversionRule(Pattern.compile("(first group)( second group)( third group)( 4th group)"));
45 // group zero is ignored during treatment
46 // replacement for the first
47 cr1.addReplacement(1, "1st group");
48 // no replacement for the second group it will remains the same
49 // empty string for the third group it will be deleted
50 cr1.addReplacement(3, "");
51 // no replacement for the third group it will remains the same
52
53 conversionRuleList = new ArrayList<ConversionRule>();
54 conversionRuleList.add(cr);
55 conversionRuleList.add(cr1);
56 }
57
58 public Iterator<ConversionRule> iterator() {
59 return conversionRuleList.iterator();
60 }
61
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 import org.slf4j.migrator.line.ConversionRule;
31 import org.slf4j.migrator.line.MultiGroupConversionRule;
32 import org.slf4j.migrator.line.RuleSet;
33 import org.slf4j.migrator.line.SingleConversionRule;
34
35 class TrivialMatcher implements RuleSet {
36
37 private ArrayList<ConversionRule> conversionRuleList;
38
39 public TrivialMatcher() {
40 // simple rule no capturing group is defined, we use default capturing group which is group zero
41 SingleConversionRule cr = new SingleConversionRule(Pattern.compile("import org.slf4j.converter"), "simple replacement with an unique capturing group");
42
43 // we define 4 differents capturing groups
44 MultiGroupConversionRule cr1 = new MultiGroupConversionRule(Pattern.compile("(first group)( second group)( third group)( 4th group)"));
45 // group zero is ignored during treatment
46 // replacement for the first
47 cr1.addReplacement(1, "1st group");
48 // no replacement for the second group it will remains the same
49 // empty string for the third group it will be deleted
50 cr1.addReplacement(3, "");
51 // no replacement for the third group it will remains the same
52
53 conversionRuleList = new ArrayList<ConversionRule>();
54 conversionRuleList.add(cr);
55 conversionRuleList.add(cr1);
56 }
57
58 public Iterator<ConversionRule> iterator() {
59 return conversionRuleList.iterator();
60 }
61
6262 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29
30 public class TrivialMatcherTest {
31
32 @Test
33 public void testSimpleReplacement() {
34 LineConverter trivialLC = new LineConverter(new TrivialMatcher());
35
36 // "import org.slf4j.converter" -- > simple replacement with an unique
37 // capturing group
38 assertEquals("simple replacement with an unique capturing group", trivialLC.getOneLineReplacement("import org.slf4j.converter"));
39
40 assertEquals("1st group second group 4th group", trivialLC.getOneLineReplacement("first group second group third group 4th group"));
41
42 }
43
44 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import static org.junit.Assert.assertEquals;
27
28 import org.junit.Test;
29
30 public class TrivialMatcherTest {
31
32 @Test
33 public void testSimpleReplacement() {
34 LineConverter trivialLC = new LineConverter(new TrivialMatcher());
35
36 // "import org.slf4j.converter" -- > simple replacement with an unique
37 // capturing group
38 assertEquals("simple replacement with an unique capturing group", trivialLC.getOneLineReplacement("import org.slf4j.converter"));
39
40 assertEquals("1st group second group 4th group", trivialLC.getOneLineReplacement("first group second group third group 4th group"));
41
42 }
43
44 }
0 Copyright (c) 2004-2007 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>slf4j-nop</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J NOP Binding</name>
16 <description>SLF4J NOP Binding</description>
17 <url>http://www.slf4j.org</url>
18
19 <dependencies>
20 <dependency>
21 <groupId>org.slf4j</groupId>
22 <artifactId>slf4j-api</artifactId>
23 </dependency>
24 </dependencies>
25
26 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>slf4j-nop</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J NOP Binding</name>
16 <description>SLF4J NOP Binding</description>
17 <url>http://www.slf4j.org</url>
18
19 <dependencies>
20 <dependency>
21 <groupId>org.slf4j</groupId>
22 <artifactId>slf4j-api</artifactId>
23 </dependency>
24 </dependencies>
25
26
27 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.helpers.NOPLoggerFactory;
29 import org.slf4j.spi.LoggerFactoryBinder;
30
31 /**
32 * The binding of {@link LoggerFactory} class with an actual instance of
33 * {@link ILoggerFactory} is performed using information returned by this class.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public class StaticLoggerBinder implements LoggerFactoryBinder {
38
39 /**
40 * The unique instance of this class.
41 *
42 */
43 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticLoggerBinder singleton
49 */
50 public static final StaticLoggerBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Declare the version of the SLF4J API this implementation is compiled against.
56 * The value of this field is modified with each major release.
57 */
58 // to avoid constant folding by the compiler, this field must *not* be final
59 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
60
61 private static final String loggerFactoryClassStr = NOPLoggerFactory.class.getName();
62
63 /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method
64 * should always be the same object
65 */
66 private final ILoggerFactory loggerFactory;
67
68 private StaticLoggerBinder() {
69 loggerFactory = new NOPLoggerFactory();
70 }
71
72 public ILoggerFactory getLoggerFactory() {
73 return loggerFactory;
74 }
75
76 public String getLoggerFactoryClassStr() {
77 return loggerFactoryClassStr;
78 }
79 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.helpers.NOPLoggerFactory;
29 import org.slf4j.spi.LoggerFactoryBinder;
30
31 /**
32 * The binding of {@link LoggerFactory} class with an actual instance of
33 * {@link ILoggerFactory} is performed using information returned by this class.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public class StaticLoggerBinder implements LoggerFactoryBinder {
38
39 /**
40 * The unique instance of this class.
41 *
42 */
43 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticLoggerBinder singleton
49 */
50 public static final StaticLoggerBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Declare the version of the SLF4J API this implementation is compiled against.
56 * The value of this field is modified with each major release.
57 */
58 // to avoid constant folding by the compiler, this field must *not* be final
59 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
60
61 private static final String loggerFactoryClassStr = NOPLoggerFactory.class.getName();
62
63 /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method
64 * should always be the same object
65 */
66 private final ILoggerFactory loggerFactory;
67
68 private StaticLoggerBinder() {
69 loggerFactory = new NOPLoggerFactory();
70 }
71
72 public ILoggerFactory getLoggerFactory() {
73 return loggerFactory;
74 }
75
76 public String getLoggerFactoryClassStr() {
77 return loggerFactoryClassStr;
78 }
79 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link NOPMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticMDCBinder singleton
48 * @since 1.7.14
49 */
50 public static final StaticMDCBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Currently this method always returns an instance of
56 * {@link StaticMDCBinder}.
57 */
58 public MDCAdapter getMDCA() {
59 return new NOPMDCAdapter();
60 }
61
62 public String getMDCAdapterClassStr() {
63 return NOPMDCAdapter.class.getName();
64 }
65 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link NOPMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticMDCBinder singleton
48 * @since 1.7.14
49 */
50 public static final StaticMDCBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Currently this method always returns an instance of
56 * {@link StaticMDCBinder}.
57 */
58 public MDCAdapter getMDCA() {
59 return new NOPMDCAdapter();
60 }
61
62 public String getMDCAdapterClassStr() {
63 return NOPMDCAdapter.class.getName();
64 }
65 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Return the singleton of this class.
52 *
53 * @return the StaticMarkerBinder singleton
54 * @since 1.7.14
55 */
56 public static StaticMarkerBinder getSingleton() {
57 return SINGLETON;
58 }
59
60 /**
61 * Currently this method always returns an instance of
62 * {@link BasicMarkerFactory}.
63 */
64 public IMarkerFactory getMarkerFactory() {
65 return markerFactory;
66 }
67
68 /**
69 * Currently, this method returns the class name of
70 * {@link BasicMarkerFactory}.
71 */
72 public String getMarkerFactoryClassStr() {
73 return BasicMarkerFactory.class.getName();
74 }
75
76 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Return the singleton of this class.
52 *
53 * @return the StaticMarkerBinder singleton
54 * @since 1.7.14
55 */
56 public static StaticMarkerBinder getSingleton() {
57 return SINGLETON;
58 }
59
60 /**
61 * Currently this method always returns an instance of
62 * {@link BasicMarkerFactory}.
63 */
64 public IMarkerFactory getMarkerFactory() {
65 return markerFactory;
66 }
67
68 /**
69 * Currently, this method returns the class name of
70 * {@link BasicMarkerFactory}.
71 */
72 public String getMarkerFactoryClassStr() {
73 return BasicMarkerFactory.class.getName();
74 }
75
76 }
0 Implementation-Title: slf4j-nop
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.nop
3 Bundle-Name: slf4j-nop
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},
8 org.slf4j.spi;version=${parsedVersion.osgiVersion},
9 org.slf4j.helpers;version=${parsedVersion.osgiVersion},
10 org.slf4j.event;version=${parsedVersion.osgiVersion}
0 Implementation-Title: slf4j-nop
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.nop
3 Bundle-Name: slf4j-nop
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},
8 org.slf4j.spi;version=${parsedVersion.osgiVersion},
9 org.slf4j.helpers;version=${parsedVersion.osgiVersion},
10 org.slf4j.event;version=${parsedVersion.osgiVersion}
1111 Fragment-Host: slf4j.api
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertNull;
27
28 import org.junit.Test;
29
30 /**
31 * Test whether invoking the SLF4J API causes problems or not.
32 *
33 * @author Ceki Gulcu
34 *
35 */
36 public class InvocationTest {
37
38 @Test
39 public void test1() {
40 Logger logger = LoggerFactory.getLogger("test1");
41 logger.debug("Hello world.");
42 }
43
44 @Test
45 public void test2() {
46 Integer i1 = new Integer(1);
47 Integer i2 = new Integer(2);
48 Integer i3 = new Integer(3);
49 Exception e = new Exception("This is a test exception.");
50 Logger logger = LoggerFactory.getLogger("test2");
51
52 logger.debug("Hello world 1.");
53 logger.debug("Hello world {}", i1);
54 logger.debug("val={} val={}", i1, i2);
55 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
56
57 logger.debug("Hello world 2", e);
58 logger.info("Hello world 2.");
59
60 logger.warn("Hello world 3.");
61 logger.warn("Hello world 3", e);
62
63 logger.error("Hello world 4.");
64 logger.error("Hello world {}", new Integer(3));
65 logger.error("Hello world 4.", e);
66 }
67
68 @Test
69 public void testNull() {
70 Logger logger = LoggerFactory.getLogger("testNull");
71 logger.debug(null);
72 logger.info(null);
73 logger.warn(null);
74 logger.error(null);
75
76 Exception e = new Exception("This is a test exception.");
77 logger.debug(null, e);
78 logger.info(null, e);
79 logger.warn(null, e);
80 logger.error(null, e);
81 }
82
83 @Test
84 public void testMarker() {
85 Logger logger = LoggerFactory.getLogger("testMarker");
86 Marker blue = MarkerFactory.getMarker("BLUE");
87 logger.debug(blue, "hello");
88 logger.info(blue, "hello");
89 logger.warn(blue, "hello");
90 logger.error(blue, "hello");
91
92 logger.debug(blue, "hello {}", "world");
93 logger.info(blue, "hello {}", "world");
94 logger.warn(blue, "hello {}", "world");
95 logger.error(blue, "hello {}", "world");
96
97 logger.debug(blue, "hello {} and {} ", "world", "universe");
98 logger.info(blue, "hello {} and {} ", "world", "universe");
99 logger.warn(blue, "hello {} and {} ", "world", "universe");
100 logger.error(blue, "hello {} and {} ", "world", "universe");
101 }
102
103 @Test
104 public void testMDC() {
105 MDC.put("k", "v");
106 assertNull(MDC.get("k"));
107 MDC.remove("k");
108 assertNull(MDC.get("k"));
109 MDC.clear();
110 }
111
112 @Test
113 public void testMDCCloseable() {
114 MDC.MDCCloseable closeable = MDC.putCloseable("k", "v");
115 assertNull(MDC.get("k"));
116 closeable.close();
117 assertNull(MDC.get("k"));
118 MDC.clear();
119 }
120 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertNull;
27
28 import org.junit.Test;
29
30 /**
31 * Test whether invoking the SLF4J API causes problems or not.
32 *
33 * @author Ceki Gulcu
34 *
35 */
36 public class InvocationTest {
37
38 @Test
39 public void test1() {
40 Logger logger = LoggerFactory.getLogger("test1");
41 logger.debug("Hello world.");
42 }
43
44 @Test
45 public void test2() {
46 Integer i1 = new Integer(1);
47 Integer i2 = new Integer(2);
48 Integer i3 = new Integer(3);
49 Exception e = new Exception("This is a test exception.");
50 Logger logger = LoggerFactory.getLogger("test2");
51
52 logger.debug("Hello world 1.");
53 logger.debug("Hello world {}", i1);
54 logger.debug("val={} val={}", i1, i2);
55 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
56
57 logger.debug("Hello world 2", e);
58 logger.info("Hello world 2.");
59
60 logger.warn("Hello world 3.");
61 logger.warn("Hello world 3", e);
62
63 logger.error("Hello world 4.");
64 logger.error("Hello world {}", new Integer(3));
65 logger.error("Hello world 4.", e);
66 }
67
68 @Test
69 public void testNull() {
70 Logger logger = LoggerFactory.getLogger("testNull");
71 logger.debug(null);
72 logger.info(null);
73 logger.warn(null);
74 logger.error(null);
75
76 Exception e = new Exception("This is a test exception.");
77 logger.debug(null, e);
78 logger.info(null, e);
79 logger.warn(null, e);
80 logger.error(null, e);
81 }
82
83 @Test
84 public void testMarker() {
85 Logger logger = LoggerFactory.getLogger("testMarker");
86 Marker blue = MarkerFactory.getMarker("BLUE");
87 logger.debug(blue, "hello");
88 logger.info(blue, "hello");
89 logger.warn(blue, "hello");
90 logger.error(blue, "hello");
91
92 logger.debug(blue, "hello {}", "world");
93 logger.info(blue, "hello {}", "world");
94 logger.warn(blue, "hello {}", "world");
95 logger.error(blue, "hello {}", "world");
96
97 logger.debug(blue, "hello {} and {} ", "world", "universe");
98 logger.info(blue, "hello {} and {} ", "world", "universe");
99 logger.warn(blue, "hello {} and {} ", "world", "universe");
100 logger.error(blue, "hello {} and {} ", "world", "universe");
101 }
102
103 @Test
104 public void testMDC() {
105 MDC.put("k", "v");
106 assertNull(MDC.get("k"));
107 MDC.remove("k");
108 assertNull(MDC.get("k"));
109 MDC.clear();
110 }
111
112 @Test
113 public void testMDCCloseable() {
114 MDC.MDCCloseable closeable = MDC.putCloseable("k", "v");
115 assertNull(MDC.get("k"));
116 closeable.close();
117 assertNull(MDC.get("k"));
118 MDC.clear();
119 }
120 }
0 package org.slf4j;
1
2 public class LoggerFactoryFriend {
3 static public void reset() {
4 LoggerFactory.reset();
5 }
6 }
0 package org.slf4j;
1
2 public class LoggerFactoryFriend {
3 static public void reset() {
4 LoggerFactory.reset();
5 }
6 }
0 /**
1 * Copyright (c) 2004-2016 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.io.PrintStream;
29 import java.util.ArrayList;
30 import java.util.List;
31 import java.util.Random;
32 import java.util.concurrent.BrokenBarrierException;
33 import java.util.concurrent.CyclicBarrier;
34 import java.util.concurrent.atomic.AtomicLong;
35
36 import org.junit.After;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.slf4j.LoggerFactoryFriend;
42
43 public class MultithreadedInitializationTest {
44
45 final static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2;
46
47 private static AtomicLong EVENT_COUNT = new AtomicLong(0);
48
49 final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1);
50
51 int diff = new Random().nextInt(10000);
52 String loggerName = "org.slf4j.impl.MultithreadedInitializationTest";
53 private final PrintStream oldErr = System.err;
54 StringPrintStream sps = new StringPrintStream(oldErr);
55
56 @Before
57 public void setup() {
58 LoggerFactoryFriend.reset();
59 System.setErr(sps);
60 }
61
62 @After
63 public void tearDown() throws Exception {
64 LoggerFactoryFriend.reset();
65 System.setErr(oldErr);
66 }
67
68 @Test
69 public void multiThreadedInitialization() throws InterruptedException, BrokenBarrierException {
70 System.out.println("THREAD_COUNT=" + THREAD_COUNT);
71 LoggerAccessingThread[] accessors = harness();
72
73 for (LoggerAccessingThread accessor : accessors) {
74 EVENT_COUNT.getAndIncrement();
75 accessor.logger.info("post harness");
76 }
77
78 Logger logger = LoggerFactory.getLogger(loggerName + ".slowInitialization-" + diff);
79 logger.info("hello");
80 EVENT_COUNT.getAndIncrement();
81
82 assertEquals(0, sps.stringList.size());
83 }
84
85 private static LoggerAccessingThread[] harness() throws InterruptedException, BrokenBarrierException {
86 LoggerAccessingThread[] threads = new LoggerAccessingThread[THREAD_COUNT];
87 final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1);
88 for (int i = 0; i < THREAD_COUNT; i++) {
89 threads[i] = new LoggerAccessingThread(barrier, i);
90 threads[i].start();
91 }
92
93 barrier.await();
94 for (int i = 0; i < THREAD_COUNT; i++) {
95 threads[i].join();
96 }
97 return threads;
98 }
99
100 static class LoggerAccessingThread extends Thread {
101 final CyclicBarrier barrier;
102 Logger logger;
103 int count;
104
105 LoggerAccessingThread(CyclicBarrier barrier, int count) {
106 this.barrier = barrier;
107 this.count = count;
108 }
109
110 public void run() {
111 try {
112 barrier.await();
113 } catch (Exception e) {
114 e.printStackTrace();
115 }
116 logger = LoggerFactory.getLogger(this.getClass().getName() + "-" + count);
117 logger.info("in run method");
118 EVENT_COUNT.getAndIncrement();
119 }
120 };
121
122 public static class StringPrintStream extends PrintStream {
123
124 public static final String LINE_SEP = System.getProperty("line.separator");
125 PrintStream other;
126 List<String> stringList = new ArrayList<String>();
127
128 public StringPrintStream(PrintStream ps) {
129 super(ps);
130 other = ps;
131 }
132
133 public void print(String s) {
134 other.print(s);
135 stringList.add(s);
136 }
137
138 public void println(String s) {
139 other.println(s);
140 stringList.add(s);
141 }
142
143 public void println(Object o) {
144 other.println(o);
145 stringList.add(o.toString());
146 }
147 };
148
149 }
0 /**
1 * Copyright (c) 2004-2016 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.io.PrintStream;
29 import java.util.ArrayList;
30 import java.util.List;
31 import java.util.Random;
32 import java.util.concurrent.BrokenBarrierException;
33 import java.util.concurrent.CyclicBarrier;
34 import java.util.concurrent.atomic.AtomicLong;
35
36 import org.junit.After;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.slf4j.LoggerFactoryFriend;
42
43 public class MultithreadedInitializationTest {
44
45 final static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2;
46
47 private static AtomicLong EVENT_COUNT = new AtomicLong(0);
48
49 final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1);
50
51 int diff = new Random().nextInt(10000);
52 String loggerName = "org.slf4j.impl.MultithreadedInitializationTest";
53 private final PrintStream oldErr = System.err;
54 StringPrintStream sps = new StringPrintStream(oldErr);
55
56 @Before
57 public void setup() {
58 LoggerFactoryFriend.reset();
59 System.setErr(sps);
60 }
61
62 @After
63 public void tearDown() throws Exception {
64 LoggerFactoryFriend.reset();
65 System.setErr(oldErr);
66 }
67
68 @Test
69 public void multiThreadedInitialization() throws InterruptedException, BrokenBarrierException {
70 System.out.println("THREAD_COUNT=" + THREAD_COUNT);
71 LoggerAccessingThread[] accessors = harness();
72
73 for (LoggerAccessingThread accessor : accessors) {
74 EVENT_COUNT.getAndIncrement();
75 accessor.logger.info("post harness");
76 }
77
78 Logger logger = LoggerFactory.getLogger(loggerName + ".slowInitialization-" + diff);
79 logger.info("hello");
80 EVENT_COUNT.getAndIncrement();
81
82 assertEquals(0, sps.stringList.size());
83 }
84
85 private static LoggerAccessingThread[] harness() throws InterruptedException, BrokenBarrierException {
86 LoggerAccessingThread[] threads = new LoggerAccessingThread[THREAD_COUNT];
87 final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1);
88 for (int i = 0; i < THREAD_COUNT; i++) {
89 threads[i] = new LoggerAccessingThread(barrier, i);
90 threads[i].start();
91 }
92
93 barrier.await();
94 for (int i = 0; i < THREAD_COUNT; i++) {
95 threads[i].join();
96 }
97 return threads;
98 }
99
100 static class LoggerAccessingThread extends Thread {
101 final CyclicBarrier barrier;
102 Logger logger;
103 int count;
104
105 LoggerAccessingThread(CyclicBarrier barrier, int count) {
106 this.barrier = barrier;
107 this.count = count;
108 }
109
110 public void run() {
111 try {
112 barrier.await();
113 } catch (Exception e) {
114 e.printStackTrace();
115 }
116 logger = LoggerFactory.getLogger(this.getClass().getName() + "-" + count);
117 logger.info("in run method");
118 EVENT_COUNT.getAndIncrement();
119 }
120 };
121
122 public static class StringPrintStream extends PrintStream {
123
124 public static final String LINE_SEP = System.getProperty("line.separator");
125 PrintStream other;
126 List<String> stringList = new ArrayList<String>();
127
128 public StringPrintStream(PrintStream ps) {
129 super(ps);
130 other = ps;
131 }
132
133 public void print(String s) {
134 other.print(s);
135 stringList.add(s);
136 }
137
138 public void println(String s) {
139 other.println(s);
140 stringList.add(s);
141 }
142
143 public void println(Object o) {
144 other.println(o);
145 stringList.add(o.toString());
146 }
147 };
148
149 }
0 Copyright (c) 2004-2007 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>slf4j-simple</artifactId>
13 <packaging>jar</packaging>
14 <name>SLF4J Simple Binding</name>
15 <description>SLF4J Simple binding</description>
16 <url>http://www.slf4j.org</url>
17
18 <dependencies>
19 <dependency>
20 <groupId>org.slf4j</groupId>
21 <artifactId>slf4j-api</artifactId>
22 </dependency>
23
24 <dependency>
25 <groupId>org.slf4j</groupId>
26 <artifactId>slf4j-api</artifactId>
27 <type>test-jar</type>
28 <version>${project.version}</version>
29 <scope>test</scope>
30 </dependency>
31 </dependencies>
32
33 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>slf4j-simple</artifactId>
13 <packaging>jar</packaging>
14 <name>SLF4J Simple Binding</name>
15 <description>SLF4J Simple binding</description>
16 <url>http://www.slf4j.org</url>
17
18 <dependencies>
19 <dependency>
20 <groupId>org.slf4j</groupId>
21 <artifactId>slf4j-api</artifactId>
22 </dependency>
23
24 <dependency>
25 <groupId>org.slf4j</groupId>
26 <artifactId>slf4j-api</artifactId>
27 <type>test-jar</type>
28 <version>${project.version}</version>
29 <scope>test</scope>
30 </dependency>
31 </dependencies>
32
33
34 </project>
0 package org.slf4j.impl;
1
2 import java.io.PrintStream;
3
4 /**
5 * This class encapsulates the user's choice of output target.
6 *
7 * @author Ceki G&uuml;lc&uuml;
8 *
9 */
10 class OutputChoice {
11
12 enum OutputChoiceType {
13 SYS_OUT, CACHED_SYS_OUT, SYS_ERR, CACHED_SYS_ERR, FILE;
14 }
15
16 final OutputChoiceType outputChoiceType;
17 final PrintStream targetPrintStream;
18
19 OutputChoice(OutputChoiceType outputChoiceType) {
20 if (outputChoiceType == OutputChoiceType.FILE) {
21 throw new IllegalArgumentException();
22 }
23 this.outputChoiceType = outputChoiceType;
24 if (outputChoiceType == OutputChoiceType.CACHED_SYS_OUT) {
25 this.targetPrintStream = System.out;
26 } else if (outputChoiceType == OutputChoiceType.CACHED_SYS_ERR) {
27 this.targetPrintStream = System.err;
28 } else {
29 this.targetPrintStream = null;
30 }
31 }
32
33 OutputChoice(PrintStream printStream) {
34 this.outputChoiceType = OutputChoiceType.FILE;
35 this.targetPrintStream = printStream;
36 }
37
38 PrintStream getTargetPrintStream() {
39 switch (outputChoiceType) {
40 case SYS_OUT:
41 return System.out;
42 case SYS_ERR:
43 return System.err;
44 case CACHED_SYS_ERR:
45 case CACHED_SYS_OUT:
46 case FILE:
47 return targetPrintStream;
48 default:
49 throw new IllegalArgumentException();
50 }
51
52 }
53
54 }
0 package org.slf4j.impl;
1
2 import java.io.PrintStream;
3
4 /**
5 * This class encapsulates the user's choice of output target.
6 *
7 * @author Ceki G&uuml;lc&uuml;
8 *
9 */
10 class OutputChoice {
11
12 enum OutputChoiceType {
13 SYS_OUT, CACHED_SYS_OUT, SYS_ERR, CACHED_SYS_ERR, FILE;
14 }
15
16 final OutputChoiceType outputChoiceType;
17 final PrintStream targetPrintStream;
18
19 OutputChoice(OutputChoiceType outputChoiceType) {
20 if (outputChoiceType == OutputChoiceType.FILE) {
21 throw new IllegalArgumentException();
22 }
23 this.outputChoiceType = outputChoiceType;
24 if (outputChoiceType == OutputChoiceType.CACHED_SYS_OUT) {
25 this.targetPrintStream = System.out;
26 } else if (outputChoiceType == OutputChoiceType.CACHED_SYS_ERR) {
27 this.targetPrintStream = System.err;
28 } else {
29 this.targetPrintStream = null;
30 }
31 }
32
33 OutputChoice(PrintStream printStream) {
34 this.outputChoiceType = OutputChoiceType.FILE;
35 this.targetPrintStream = printStream;
36 }
37
38 PrintStream getTargetPrintStream() {
39 switch (outputChoiceType) {
40 case SYS_OUT:
41 return System.out;
42 case SYS_ERR:
43 return System.err;
44 case CACHED_SYS_ERR:
45 case CACHED_SYS_OUT:
46 case FILE:
47 return targetPrintStream;
48 default:
49 throw new IllegalArgumentException();
50 }
51
52 }
53
54 }
0 /**
1 * Copyright (c) 2004-2012 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.io.PrintStream;
27 import java.util.Date;
28
29 import org.slf4j.Logger;
30 import org.slf4j.event.LoggingEvent;
31 import org.slf4j.helpers.FormattingTuple;
32 import org.slf4j.helpers.MarkerIgnoringBase;
33 import org.slf4j.helpers.MessageFormatter;
34 import org.slf4j.spi.LocationAwareLogger;
35
36 /**
37 * <p>
38 * Simple implementation of {@link Logger} that sends all enabled log messages,
39 * for all defined loggers, to the console ({@code System.err}). The following
40 * system properties are supported to configure the behavior of this logger:
41 * </p>
42 *
43 * <ul>
44 * <li><code>org.slf4j.simpleLogger.logFile</code> - The output target which can
45 * be the <em>path</em> to a file, or the special values "System.out" and
46 * "System.err". Default is "System.err".</li>
47 *
48 * <li><code>org.slf4j.simpleLogger.cacheOutputStream</code> - If the output
49 * target is set to "System.out" or "System.err" (see preceding entry), by
50 * default, logs will be output to the latest value referenced by
51 * <code>System.out/err</code> variables. By setting this
52 * parameter to true, the output stream will be cached, i.e. assigned once at
53 * initialization time and re-used independently of the current value referenced by
54 * <code>System.out/err</code>.
55 * </li>
56 *
57 * <li><code>org.slf4j.simpleLogger.defaultLogLevel</code> - Default log level
58 * for all instances of SimpleLogger. Must be one of ("trace", "debug", "info",
59 * "warn", "error" or "off"). If not specified, defaults to "info".</li>
60 *
61 * <li><code>org.slf4j.simpleLogger.log.<em>a.b.c</em></code> - Logging detail
62 * level for a SimpleLogger instance named "a.b.c". Right-side value must be one
63 * of "trace", "debug", "info", "warn", "error" or "off". When a SimpleLogger
64 * named "a.b.c" is initialized, its level is assigned from this property. If
65 * unspecified, the level of nearest parent logger will be used, and if none is
66 * set, then the value specified by
67 * <code>org.slf4j.simpleLogger.defaultLogLevel</code> will be used.</li>
68 *
69 * <li><code>org.slf4j.simpleLogger.showDateTime</code> - Set to
70 * <code>true</code> if you want the current date and time to be included in
71 * output messages. Default is <code>false</code></li>
72 *
73 * <li><code>org.slf4j.simpleLogger.dateTimeFormat</code> - The date and time
74 * format to be used in the output messages. The pattern describing the date and
75 * time format is defined by <a href=
76 * "http://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html">
77 * <code>SimpleDateFormat</code></a>. If the format is not specified or is
78 * invalid, the number of milliseconds since start up will be output.</li>
79 *
80 * <li><code>org.slf4j.simpleLogger.showThreadName</code> -Set to
81 * <code>true</code> if you want to output the current thread name. Defaults to
82 * <code>true</code>.</li>
83 *
84 * <li><code>org.slf4j.simpleLogger.showLogName</code> - Set to
85 * <code>true</code> if you want the Logger instance name to be included in
86 * output messages. Defaults to <code>true</code>.</li>
87 *
88 * <li><code>org.slf4j.simpleLogger.showShortLogName</code> - Set to
89 * <code>true</code> if you want the last component of the name to be included
90 * in output messages. Defaults to <code>false</code>.</li>
91 *
92 * <li><code>org.slf4j.simpleLogger.levelInBrackets</code> - Should the level
93 * string be output in brackets? Defaults to <code>false</code>.</li>
94 *
95 * <li><code>org.slf4j.simpleLogger.warnLevelString</code> - The string value
96 * output for the warn level. Defaults to <code>WARN</code>.</li>
97 *
98 * </ul>
99 *
100 * <p>
101 * In addition to looking for system properties with the names specified above,
102 * this implementation also checks for a class loader resource named
103 * <code>"simplelogger.properties"</code>, and includes any matching definitions
104 * from this resource (if it exists).
105 * </p>
106 *
107 * <p>
108 * With no configuration, the default output includes the relative time in
109 * milliseconds, thread name, the level, logger name, and the message followed
110 * by the line separator for the host. In log4j terms it amounts to the "%r [%t]
111 * %level %logger - %m%n" pattern.
112 * </p>
113 * <p>
114 * Sample output follows.
115 * </p>
116 *
117 * <pre>
118 * 176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse order.
119 * 225 [main] INFO examples.SortAlgo - Entered the sort method.
120 * 304 [main] INFO examples.SortAlgo - Dump of integer array:
121 * 317 [main] INFO examples.SortAlgo - Element [0] = 0
122 * 331 [main] INFO examples.SortAlgo - Element [1] = 1
123 * 343 [main] INFO examples.Sort - The next log statement should be an error message.
124 * 346 [main] ERROR examples.SortAlgo - Tried to dump an uninitialized array.
125 * at org.log4j.examples.SortAlgo.dump(SortAlgo.java:58)
126 * at org.log4j.examples.Sort.main(Sort.java:64)
127 * 467 [main] INFO examples.Sort - Exiting main method.
128 * </pre>
129 *
130 * <p>
131 * This implementation is heavily inspired by
132 * <a href="http://commons.apache.org/logging/">Apache Commons Logging</a>'s
133 * SimpleLog.
134 * </p>
135 *
136 * @author Ceki G&uuml;lc&uuml;
137 * @author Scott Sanders
138 * @author Rod Waldhoff
139 * @author Robert Burrell Donkin
140 * @author C&eacute;drik LIME
141 */
142 public class SimpleLogger extends MarkerIgnoringBase {
143
144 private static final long serialVersionUID = -632788891211436180L;
145
146 private static long START_TIME = System.currentTimeMillis();
147
148 protected static final int LOG_LEVEL_TRACE = LocationAwareLogger.TRACE_INT;
149 protected static final int LOG_LEVEL_DEBUG = LocationAwareLogger.DEBUG_INT;
150 protected static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT;
151 protected static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT;
152 protected static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT;
153 // The OFF level can only be used in configuration files to disable logging.
154 // It has
155 // no printing method associated with it in o.s.Logger interface.
156 protected static final int LOG_LEVEL_OFF = LOG_LEVEL_ERROR + 10;
157
158 private static boolean INITIALIZED = false;
159 static SimpleLoggerConfiguration CONFIG_PARAMS = null;
160
161 static void lazyInit() {
162 if (INITIALIZED) {
163 return;
164 }
165 INITIALIZED = true;
166 init();
167 }
168
169 // external software might be invoking this method directly. Do not rename
170 // or change its semantics.
171 static void init() {
172 CONFIG_PARAMS = new SimpleLoggerConfiguration();
173 CONFIG_PARAMS.init();
174 }
175
176 /** The current log level */
177 protected int currentLogLevel = LOG_LEVEL_INFO;
178 /** The short name of this simple log instance */
179 private transient String shortLogName = null;
180
181 /**
182 * All system properties used by <code>SimpleLogger</code> start with this
183 * prefix
184 */
185 public static final String SYSTEM_PREFIX = "org.slf4j.simpleLogger.";
186
187 public static final String LOG_KEY_PREFIX = SimpleLogger.SYSTEM_PREFIX + "log.";
188
189 public static final String CACHE_OUTPUT_STREAM_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "cacheOutputStream";
190
191 public static final String WARN_LEVEL_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "warnLevelString";
192
193 public static final String LEVEL_IN_BRACKETS_KEY = SimpleLogger.SYSTEM_PREFIX + "levelInBrackets";
194
195 public static final String LOG_FILE_KEY = SimpleLogger.SYSTEM_PREFIX + "logFile";
196
197 public static final String SHOW_SHORT_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showShortLogName";
198
199 public static final String SHOW_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showLogName";
200
201 public static final String SHOW_THREAD_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showThreadName";
202
203 public static final String DATE_TIME_FORMAT_KEY = SimpleLogger.SYSTEM_PREFIX + "dateTimeFormat";
204
205 public static final String SHOW_DATE_TIME_KEY = SimpleLogger.SYSTEM_PREFIX + "showDateTime";
206
207 public static final String DEFAULT_LOG_LEVEL_KEY = SimpleLogger.SYSTEM_PREFIX + "defaultLogLevel";
208
209 /**
210 * Package access allows only {@link SimpleLoggerFactory} to instantiate
211 * SimpleLogger instances.
212 */
213 SimpleLogger(String name) {
214 this.name = name;
215
216 String levelString = recursivelyComputeLevelString();
217 if (levelString != null) {
218 this.currentLogLevel = SimpleLoggerConfiguration.stringToLevel(levelString);
219 } else {
220 this.currentLogLevel = CONFIG_PARAMS.defaultLogLevel;
221 }
222 }
223
224 String recursivelyComputeLevelString() {
225 String tempName = name;
226 String levelString = null;
227 int indexOfLastDot = tempName.length();
228 while ((levelString == null) && (indexOfLastDot > -1)) {
229 tempName = tempName.substring(0, indexOfLastDot);
230 levelString = CONFIG_PARAMS.getStringProperty(SimpleLogger.LOG_KEY_PREFIX + tempName, null);
231 indexOfLastDot = String.valueOf(tempName).lastIndexOf(".");
232 }
233 return levelString;
234 }
235
236 /**
237 * This is our internal implementation for logging regular
238 * (non-parameterized) log messages.
239 *
240 * @param level
241 * One of the LOG_LEVEL_XXX constants defining the log level
242 * @param message
243 * The message itself
244 * @param t
245 * The exception whose stack trace should be logged
246 */
247 private void log(int level, String message, Throwable t) {
248 if (!isLevelEnabled(level)) {
249 return;
250 }
251
252 StringBuilder buf = new StringBuilder(32);
253
254 // Append date-time if so configured
255 if (CONFIG_PARAMS.showDateTime) {
256 if (CONFIG_PARAMS.dateFormatter != null) {
257 buf.append(getFormattedDate());
258 buf.append(' ');
259 } else {
260 buf.append(System.currentTimeMillis() - START_TIME);
261 buf.append(' ');
262 }
263 }
264
265 // Append current thread name if so configured
266 if (CONFIG_PARAMS.showThreadName) {
267 buf.append('[');
268 buf.append(Thread.currentThread().getName());
269 buf.append("] ");
270 }
271
272 if (CONFIG_PARAMS.levelInBrackets)
273 buf.append('[');
274
275 // Append a readable representation of the log level
276 String levelStr = renderLevel(level);
277 buf.append(levelStr);
278 if (CONFIG_PARAMS.levelInBrackets)
279 buf.append(']');
280 buf.append(' ');
281
282 // Append the name of the log instance if so configured
283 if (CONFIG_PARAMS.showShortLogName) {
284 if (shortLogName == null)
285 shortLogName = computeShortName();
286 buf.append(String.valueOf(shortLogName)).append(" - ");
287 } else if (CONFIG_PARAMS.showLogName) {
288 buf.append(String.valueOf(name)).append(" - ");
289 }
290
291 // Append the message
292 buf.append(message);
293
294 write(buf, t);
295
296 }
297
298 protected String renderLevel(int level) {
299 switch (level) {
300 case LOG_LEVEL_TRACE:
301 return "TRACE";
302 case LOG_LEVEL_DEBUG:
303 return ("DEBUG");
304 case LOG_LEVEL_INFO:
305 return "INFO";
306 case LOG_LEVEL_WARN:
307 return CONFIG_PARAMS.warnLevelString;
308 case LOG_LEVEL_ERROR:
309 return "ERROR";
310 }
311 throw new IllegalStateException("Unrecognized level [" + level + "]");
312 }
313
314 void write(StringBuilder buf, Throwable t) {
315 PrintStream targetStream = CONFIG_PARAMS.outputChoice.getTargetPrintStream();
316
317 targetStream.println(buf.toString());
318 writeThrowable(t, targetStream);
319 targetStream.flush();
320 }
321
322 protected void writeThrowable(Throwable t, PrintStream targetStream) {
323 if (t != null) {
324 t.printStackTrace(targetStream);
325 }
326 }
327
328 private String getFormattedDate() {
329 Date now = new Date();
330 String dateText;
331 synchronized (CONFIG_PARAMS.dateFormatter) {
332 dateText = CONFIG_PARAMS.dateFormatter.format(now);
333 }
334 return dateText;
335 }
336
337 private String computeShortName() {
338 return name.substring(name.lastIndexOf(".") + 1);
339 }
340
341 /**
342 * For formatted messages, first substitute arguments and then log.
343 *
344 * @param level
345 * @param format
346 * @param arg1
347 * @param arg2
348 */
349 private void formatAndLog(int level, String format, Object arg1, Object arg2) {
350 if (!isLevelEnabled(level)) {
351 return;
352 }
353 FormattingTuple tp = MessageFormatter.format(format, arg1, arg2);
354 log(level, tp.getMessage(), tp.getThrowable());
355 }
356
357 /**
358 * For formatted messages, first substitute arguments and then log.
359 *
360 * @param level
361 * @param format
362 * @param arguments
363 * a list of 3 ore more arguments
364 */
365 private void formatAndLog(int level, String format, Object... arguments) {
366 if (!isLevelEnabled(level)) {
367 return;
368 }
369 FormattingTuple tp = MessageFormatter.arrayFormat(format, arguments);
370 log(level, tp.getMessage(), tp.getThrowable());
371 }
372
373 /**
374 * Is the given log level currently enabled?
375 *
376 * @param logLevel
377 * is this level enabled?
378 */
379 protected boolean isLevelEnabled(int logLevel) {
380 // log level are numerically ordered so can use simple numeric
381 // comparison
382 return (logLevel >= currentLogLevel);
383 }
384
385 /** Are {@code trace} messages currently enabled? */
386 public boolean isTraceEnabled() {
387 return isLevelEnabled(LOG_LEVEL_TRACE);
388 }
389
390 /**
391 * A simple implementation which logs messages of level TRACE according to
392 * the format outlined above.
393 */
394 public void trace(String msg) {
395 log(LOG_LEVEL_TRACE, msg, null);
396 }
397
398 /**
399 * Perform single parameter substitution before logging the message of level
400 * TRACE according to the format outlined above.
401 */
402 public void trace(String format, Object param1) {
403 formatAndLog(LOG_LEVEL_TRACE, format, param1, null);
404 }
405
406 /**
407 * Perform double parameter substitution before logging the message of level
408 * TRACE according to the format outlined above.
409 */
410 public void trace(String format, Object param1, Object param2) {
411 formatAndLog(LOG_LEVEL_TRACE, format, param1, param2);
412 }
413
414 /**
415 * Perform double parameter substitution before logging the message of level
416 * TRACE according to the format outlined above.
417 */
418 public void trace(String format, Object... argArray) {
419 formatAndLog(LOG_LEVEL_TRACE, format, argArray);
420 }
421
422 /** Log a message of level TRACE, including an exception. */
423 public void trace(String msg, Throwable t) {
424 log(LOG_LEVEL_TRACE, msg, t);
425 }
426
427 /** Are {@code debug} messages currently enabled? */
428 public boolean isDebugEnabled() {
429 return isLevelEnabled(LOG_LEVEL_DEBUG);
430 }
431
432 /**
433 * A simple implementation which logs messages of level DEBUG according to
434 * the format outlined above.
435 */
436 public void debug(String msg) {
437 log(LOG_LEVEL_DEBUG, msg, null);
438 }
439
440 /**
441 * Perform single parameter substitution before logging the message of level
442 * DEBUG according to the format outlined above.
443 */
444 public void debug(String format, Object param1) {
445 formatAndLog(LOG_LEVEL_DEBUG, format, param1, null);
446 }
447
448 /**
449 * Perform double parameter substitution before logging the message of level
450 * DEBUG according to the format outlined above.
451 */
452 public void debug(String format, Object param1, Object param2) {
453 formatAndLog(LOG_LEVEL_DEBUG, format, param1, param2);
454 }
455
456 /**
457 * Perform double parameter substitution before logging the message of level
458 * DEBUG according to the format outlined above.
459 */
460 public void debug(String format, Object... argArray) {
461 formatAndLog(LOG_LEVEL_DEBUG, format, argArray);
462 }
463
464 /** Log a message of level DEBUG, including an exception. */
465 public void debug(String msg, Throwable t) {
466 log(LOG_LEVEL_DEBUG, msg, t);
467 }
468
469 /** Are {@code info} messages currently enabled? */
470 public boolean isInfoEnabled() {
471 return isLevelEnabled(LOG_LEVEL_INFO);
472 }
473
474 /**
475 * A simple implementation which logs messages of level INFO according to
476 * the format outlined above.
477 */
478 public void info(String msg) {
479 log(LOG_LEVEL_INFO, msg, null);
480 }
481
482 /**
483 * Perform single parameter substitution before logging the message of level
484 * INFO according to the format outlined above.
485 */
486 public void info(String format, Object arg) {
487 formatAndLog(LOG_LEVEL_INFO, format, arg, null);
488 }
489
490 /**
491 * Perform double parameter substitution before logging the message of level
492 * INFO according to the format outlined above.
493 */
494 public void info(String format, Object arg1, Object arg2) {
495 formatAndLog(LOG_LEVEL_INFO, format, arg1, arg2);
496 }
497
498 /**
499 * Perform double parameter substitution before logging the message of level
500 * INFO according to the format outlined above.
501 */
502 public void info(String format, Object... argArray) {
503 formatAndLog(LOG_LEVEL_INFO, format, argArray);
504 }
505
506 /** Log a message of level INFO, including an exception. */
507 public void info(String msg, Throwable t) {
508 log(LOG_LEVEL_INFO, msg, t);
509 }
510
511 /** Are {@code warn} messages currently enabled? */
512 public boolean isWarnEnabled() {
513 return isLevelEnabled(LOG_LEVEL_WARN);
514 }
515
516 /**
517 * A simple implementation which always logs messages of level WARN
518 * according to the format outlined above.
519 */
520 public void warn(String msg) {
521 log(LOG_LEVEL_WARN, msg, null);
522 }
523
524 /**
525 * Perform single parameter substitution before logging the message of level
526 * WARN according to the format outlined above.
527 */
528 public void warn(String format, Object arg) {
529 formatAndLog(LOG_LEVEL_WARN, format, arg, null);
530 }
531
532 /**
533 * Perform double parameter substitution before logging the message of level
534 * WARN according to the format outlined above.
535 */
536 public void warn(String format, Object arg1, Object arg2) {
537 formatAndLog(LOG_LEVEL_WARN, format, arg1, arg2);
538 }
539
540 /**
541 * Perform double parameter substitution before logging the message of level
542 * WARN according to the format outlined above.
543 */
544 public void warn(String format, Object... argArray) {
545 formatAndLog(LOG_LEVEL_WARN, format, argArray);
546 }
547
548 /** Log a message of level WARN, including an exception. */
549 public void warn(String msg, Throwable t) {
550 log(LOG_LEVEL_WARN, msg, t);
551 }
552
553 /** Are {@code error} messages currently enabled? */
554 public boolean isErrorEnabled() {
555 return isLevelEnabled(LOG_LEVEL_ERROR);
556 }
557
558 /**
559 * A simple implementation which always logs messages of level ERROR
560 * according to the format outlined above.
561 */
562 public void error(String msg) {
563 log(LOG_LEVEL_ERROR, msg, null);
564 }
565
566 /**
567 * Perform single parameter substitution before logging the message of level
568 * ERROR according to the format outlined above.
569 */
570 public void error(String format, Object arg) {
571 formatAndLog(LOG_LEVEL_ERROR, format, arg, null);
572 }
573
574 /**
575 * Perform double parameter substitution before logging the message of level
576 * ERROR according to the format outlined above.
577 */
578 public void error(String format, Object arg1, Object arg2) {
579 formatAndLog(LOG_LEVEL_ERROR, format, arg1, arg2);
580 }
581
582 /**
583 * Perform double parameter substitution before logging the message of level
584 * ERROR according to the format outlined above.
585 */
586 public void error(String format, Object... argArray) {
587 formatAndLog(LOG_LEVEL_ERROR, format, argArray);
588 }
589
590 /** Log a message of level ERROR, including an exception. */
591 public void error(String msg, Throwable t) {
592 log(LOG_LEVEL_ERROR, msg, t);
593 }
594
595 public void log(LoggingEvent event) {
596 int levelInt = event.getLevel().toInt();
597
598 if (!isLevelEnabled(levelInt)) {
599 return;
600 }
601 FormattingTuple tp = MessageFormatter.arrayFormat(event.getMessage(), event.getArgumentArray(), event.getThrowable());
602 log(levelInt, tp.getMessage(), event.getThrowable());
603 }
604
605 }
0 /**
1 * Copyright (c) 2004-2012 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.io.PrintStream;
27 import java.util.Date;
28
29 import org.slf4j.Logger;
30 import org.slf4j.event.LoggingEvent;
31 import org.slf4j.helpers.FormattingTuple;
32 import org.slf4j.helpers.MarkerIgnoringBase;
33 import org.slf4j.helpers.MessageFormatter;
34 import org.slf4j.spi.LocationAwareLogger;
35
36 /**
37 * <p>
38 * Simple implementation of {@link Logger} that sends all enabled log messages,
39 * for all defined loggers, to the console ({@code System.err}). The following
40 * system properties are supported to configure the behavior of this logger:
41 * </p>
42 *
43 * <ul>
44 * <li><code>org.slf4j.simpleLogger.logFile</code> - The output target which can
45 * be the <em>path</em> to a file, or the special values "System.out" and
46 * "System.err". Default is "System.err".</li>
47 *
48 * <li><code>org.slf4j.simpleLogger.cacheOutputStream</code> - If the output
49 * target is set to "System.out" or "System.err" (see preceding entry), by
50 * default, logs will be output to the latest value referenced by
51 * <code>System.out/err</code> variables. By setting this
52 * parameter to true, the output stream will be cached, i.e. assigned once at
53 * initialization time and re-used independently of the current value referenced by
54 * <code>System.out/err</code>.
55 * </li>
56 *
57 * <li><code>org.slf4j.simpleLogger.defaultLogLevel</code> - Default log level
58 * for all instances of SimpleLogger. Must be one of ("trace", "debug", "info",
59 * "warn", "error" or "off"). If not specified, defaults to "info".</li>
60 *
61 * <li><code>org.slf4j.simpleLogger.log.<em>a.b.c</em></code> - Logging detail
62 * level for a SimpleLogger instance named "a.b.c". Right-side value must be one
63 * of "trace", "debug", "info", "warn", "error" or "off". When a SimpleLogger
64 * named "a.b.c" is initialized, its level is assigned from this property. If
65 * unspecified, the level of nearest parent logger will be used, and if none is
66 * set, then the value specified by
67 * <code>org.slf4j.simpleLogger.defaultLogLevel</code> will be used.</li>
68 *
69 * <li><code>org.slf4j.simpleLogger.showDateTime</code> - Set to
70 * <code>true</code> if you want the current date and time to be included in
71 * output messages. Default is <code>false</code></li>
72 *
73 * <li><code>org.slf4j.simpleLogger.dateTimeFormat</code> - The date and time
74 * format to be used in the output messages. The pattern describing the date and
75 * time format is defined by <a href=
76 * "http://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html">
77 * <code>SimpleDateFormat</code></a>. If the format is not specified or is
78 * invalid, the number of milliseconds since start up will be output.</li>
79 *
80 * <li><code>org.slf4j.simpleLogger.showThreadName</code> -Set to
81 * <code>true</code> if you want to output the current thread name. Defaults to
82 * <code>true</code>.</li>
83 *
84 * <li><code>org.slf4j.simpleLogger.showLogName</code> - Set to
85 * <code>true</code> if you want the Logger instance name to be included in
86 * output messages. Defaults to <code>true</code>.</li>
87 *
88 * <li><code>org.slf4j.simpleLogger.showShortLogName</code> - Set to
89 * <code>true</code> if you want the last component of the name to be included
90 * in output messages. Defaults to <code>false</code>.</li>
91 *
92 * <li><code>org.slf4j.simpleLogger.levelInBrackets</code> - Should the level
93 * string be output in brackets? Defaults to <code>false</code>.</li>
94 *
95 * <li><code>org.slf4j.simpleLogger.warnLevelString</code> - The string value
96 * output for the warn level. Defaults to <code>WARN</code>.</li>
97 *
98 * </ul>
99 *
100 * <p>
101 * In addition to looking for system properties with the names specified above,
102 * this implementation also checks for a class loader resource named
103 * <code>"simplelogger.properties"</code>, and includes any matching definitions
104 * from this resource (if it exists).
105 * </p>
106 *
107 * <p>
108 * With no configuration, the default output includes the relative time in
109 * milliseconds, thread name, the level, logger name, and the message followed
110 * by the line separator for the host. In log4j terms it amounts to the "%r [%t]
111 * %level %logger - %m%n" pattern.
112 * </p>
113 * <p>
114 * Sample output follows.
115 * </p>
116 *
117 * <pre>
118 * 176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse order.
119 * 225 [main] INFO examples.SortAlgo - Entered the sort method.
120 * 304 [main] INFO examples.SortAlgo - Dump of integer array:
121 * 317 [main] INFO examples.SortAlgo - Element [0] = 0
122 * 331 [main] INFO examples.SortAlgo - Element [1] = 1
123 * 343 [main] INFO examples.Sort - The next log statement should be an error message.
124 * 346 [main] ERROR examples.SortAlgo - Tried to dump an uninitialized array.
125 * at org.log4j.examples.SortAlgo.dump(SortAlgo.java:58)
126 * at org.log4j.examples.Sort.main(Sort.java:64)
127 * 467 [main] INFO examples.Sort - Exiting main method.
128 * </pre>
129 *
130 * <p>
131 * This implementation is heavily inspired by
132 * <a href="http://commons.apache.org/logging/">Apache Commons Logging</a>'s
133 * SimpleLog.
134 * </p>
135 *
136 * @author Ceki G&uuml;lc&uuml;
137 * @author Scott Sanders
138 * @author Rod Waldhoff
139 * @author Robert Burrell Donkin
140 * @author C&eacute;drik LIME
141 */
142 public class SimpleLogger extends MarkerIgnoringBase {
143
144 private static final long serialVersionUID = -632788891211436180L;
145
146 private static long START_TIME = System.currentTimeMillis();
147
148 protected static final int LOG_LEVEL_TRACE = LocationAwareLogger.TRACE_INT;
149 protected static final int LOG_LEVEL_DEBUG = LocationAwareLogger.DEBUG_INT;
150 protected static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT;
151 protected static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT;
152 protected static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT;
153 // The OFF level can only be used in configuration files to disable logging.
154 // It has
155 // no printing method associated with it in o.s.Logger interface.
156 protected static final int LOG_LEVEL_OFF = LOG_LEVEL_ERROR + 10;
157
158 private static boolean INITIALIZED = false;
159 static SimpleLoggerConfiguration CONFIG_PARAMS = null;
160
161 static void lazyInit() {
162 if (INITIALIZED) {
163 return;
164 }
165 INITIALIZED = true;
166 init();
167 }
168
169 // external software might be invoking this method directly. Do not rename
170 // or change its semantics.
171 static void init() {
172 CONFIG_PARAMS = new SimpleLoggerConfiguration();
173 CONFIG_PARAMS.init();
174 }
175
176 /** The current log level */
177 protected int currentLogLevel = LOG_LEVEL_INFO;
178 /** The short name of this simple log instance */
179 private transient String shortLogName = null;
180
181 /**
182 * All system properties used by <code>SimpleLogger</code> start with this
183 * prefix
184 */
185 public static final String SYSTEM_PREFIX = "org.slf4j.simpleLogger.";
186
187 public static final String LOG_KEY_PREFIX = SimpleLogger.SYSTEM_PREFIX + "log.";
188
189 public static final String CACHE_OUTPUT_STREAM_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "cacheOutputStream";
190
191 public static final String WARN_LEVEL_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "warnLevelString";
192
193 public static final String LEVEL_IN_BRACKETS_KEY = SimpleLogger.SYSTEM_PREFIX + "levelInBrackets";
194
195 public static final String LOG_FILE_KEY = SimpleLogger.SYSTEM_PREFIX + "logFile";
196
197 public static final String SHOW_SHORT_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showShortLogName";
198
199 public static final String SHOW_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showLogName";
200
201 public static final String SHOW_THREAD_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showThreadName";
202
203 public static final String DATE_TIME_FORMAT_KEY = SimpleLogger.SYSTEM_PREFIX + "dateTimeFormat";
204
205 public static final String SHOW_DATE_TIME_KEY = SimpleLogger.SYSTEM_PREFIX + "showDateTime";
206
207 public static final String DEFAULT_LOG_LEVEL_KEY = SimpleLogger.SYSTEM_PREFIX + "defaultLogLevel";
208
209 /**
210 * Package access allows only {@link SimpleLoggerFactory} to instantiate
211 * SimpleLogger instances.
212 */
213 SimpleLogger(String name) {
214 this.name = name;
215
216 String levelString = recursivelyComputeLevelString();
217 if (levelString != null) {
218 this.currentLogLevel = SimpleLoggerConfiguration.stringToLevel(levelString);
219 } else {
220 this.currentLogLevel = CONFIG_PARAMS.defaultLogLevel;
221 }
222 }
223
224 String recursivelyComputeLevelString() {
225 String tempName = name;
226 String levelString = null;
227 int indexOfLastDot = tempName.length();
228 while ((levelString == null) && (indexOfLastDot > -1)) {
229 tempName = tempName.substring(0, indexOfLastDot);
230 levelString = CONFIG_PARAMS.getStringProperty(SimpleLogger.LOG_KEY_PREFIX + tempName, null);
231 indexOfLastDot = String.valueOf(tempName).lastIndexOf(".");
232 }
233 return levelString;
234 }
235
236 /**
237 * This is our internal implementation for logging regular
238 * (non-parameterized) log messages.
239 *
240 * @param level
241 * One of the LOG_LEVEL_XXX constants defining the log level
242 * @param message
243 * The message itself
244 * @param t
245 * The exception whose stack trace should be logged
246 */
247 private void log(int level, String message, Throwable t) {
248 if (!isLevelEnabled(level)) {
249 return;
250 }
251
252 StringBuilder buf = new StringBuilder(32);
253
254 // Append date-time if so configured
255 if (CONFIG_PARAMS.showDateTime) {
256 if (CONFIG_PARAMS.dateFormatter != null) {
257 buf.append(getFormattedDate());
258 buf.append(' ');
259 } else {
260 buf.append(System.currentTimeMillis() - START_TIME);
261 buf.append(' ');
262 }
263 }
264
265 // Append current thread name if so configured
266 if (CONFIG_PARAMS.showThreadName) {
267 buf.append('[');
268 buf.append(Thread.currentThread().getName());
269 buf.append("] ");
270 }
271
272 if (CONFIG_PARAMS.levelInBrackets)
273 buf.append('[');
274
275 // Append a readable representation of the log level
276 String levelStr = renderLevel(level);
277 buf.append(levelStr);
278 if (CONFIG_PARAMS.levelInBrackets)
279 buf.append(']');
280 buf.append(' ');
281
282 // Append the name of the log instance if so configured
283 if (CONFIG_PARAMS.showShortLogName) {
284 if (shortLogName == null)
285 shortLogName = computeShortName();
286 buf.append(String.valueOf(shortLogName)).append(" - ");
287 } else if (CONFIG_PARAMS.showLogName) {
288 buf.append(String.valueOf(name)).append(" - ");
289 }
290
291 // Append the message
292 buf.append(message);
293
294 write(buf, t);
295
296 }
297
298 protected String renderLevel(int level) {
299 switch (level) {
300 case LOG_LEVEL_TRACE:
301 return "TRACE";
302 case LOG_LEVEL_DEBUG:
303 return ("DEBUG");
304 case LOG_LEVEL_INFO:
305 return "INFO";
306 case LOG_LEVEL_WARN:
307 return CONFIG_PARAMS.warnLevelString;
308 case LOG_LEVEL_ERROR:
309 return "ERROR";
310 }
311 throw new IllegalStateException("Unrecognized level [" + level + "]");
312 }
313
314 void write(StringBuilder buf, Throwable t) {
315 PrintStream targetStream = CONFIG_PARAMS.outputChoice.getTargetPrintStream();
316
317 targetStream.println(buf.toString());
318 writeThrowable(t, targetStream);
319 targetStream.flush();
320 }
321
322 protected void writeThrowable(Throwable t, PrintStream targetStream) {
323 if (t != null) {
324 t.printStackTrace(targetStream);
325 }
326 }
327
328 private String getFormattedDate() {
329 Date now = new Date();
330 String dateText;
331 synchronized (CONFIG_PARAMS.dateFormatter) {
332 dateText = CONFIG_PARAMS.dateFormatter.format(now);
333 }
334 return dateText;
335 }
336
337 private String computeShortName() {
338 return name.substring(name.lastIndexOf(".") + 1);
339 }
340
341 /**
342 * For formatted messages, first substitute arguments and then log.
343 *
344 * @param level
345 * @param format
346 * @param arg1
347 * @param arg2
348 */
349 private void formatAndLog(int level, String format, Object arg1, Object arg2) {
350 if (!isLevelEnabled(level)) {
351 return;
352 }
353 FormattingTuple tp = MessageFormatter.format(format, arg1, arg2);
354 log(level, tp.getMessage(), tp.getThrowable());
355 }
356
357 /**
358 * For formatted messages, first substitute arguments and then log.
359 *
360 * @param level
361 * @param format
362 * @param arguments
363 * a list of 3 ore more arguments
364 */
365 private void formatAndLog(int level, String format, Object... arguments) {
366 if (!isLevelEnabled(level)) {
367 return;
368 }
369 FormattingTuple tp = MessageFormatter.arrayFormat(format, arguments);
370 log(level, tp.getMessage(), tp.getThrowable());
371 }
372
373 /**
374 * Is the given log level currently enabled?
375 *
376 * @param logLevel
377 * is this level enabled?
378 */
379 protected boolean isLevelEnabled(int logLevel) {
380 // log level are numerically ordered so can use simple numeric
381 // comparison
382 return (logLevel >= currentLogLevel);
383 }
384
385 /** Are {@code trace} messages currently enabled? */
386 public boolean isTraceEnabled() {
387 return isLevelEnabled(LOG_LEVEL_TRACE);
388 }
389
390 /**
391 * A simple implementation which logs messages of level TRACE according to
392 * the format outlined above.
393 */
394 public void trace(String msg) {
395 log(LOG_LEVEL_TRACE, msg, null);
396 }
397
398 /**
399 * Perform single parameter substitution before logging the message of level
400 * TRACE according to the format outlined above.
401 */
402 public void trace(String format, Object param1) {
403 formatAndLog(LOG_LEVEL_TRACE, format, param1, null);
404 }
405
406 /**
407 * Perform double parameter substitution before logging the message of level
408 * TRACE according to the format outlined above.
409 */
410 public void trace(String format, Object param1, Object param2) {
411 formatAndLog(LOG_LEVEL_TRACE, format, param1, param2);
412 }
413
414 /**
415 * Perform double parameter substitution before logging the message of level
416 * TRACE according to the format outlined above.
417 */
418 public void trace(String format, Object... argArray) {
419 formatAndLog(LOG_LEVEL_TRACE, format, argArray);
420 }
421
422 /** Log a message of level TRACE, including an exception. */
423 public void trace(String msg, Throwable t) {
424 log(LOG_LEVEL_TRACE, msg, t);
425 }
426
427 /** Are {@code debug} messages currently enabled? */
428 public boolean isDebugEnabled() {
429 return isLevelEnabled(LOG_LEVEL_DEBUG);
430 }
431
432 /**
433 * A simple implementation which logs messages of level DEBUG according to
434 * the format outlined above.
435 */
436 public void debug(String msg) {
437 log(LOG_LEVEL_DEBUG, msg, null);
438 }
439
440 /**
441 * Perform single parameter substitution before logging the message of level
442 * DEBUG according to the format outlined above.
443 */
444 public void debug(String format, Object param1) {
445 formatAndLog(LOG_LEVEL_DEBUG, format, param1, null);
446 }
447
448 /**
449 * Perform double parameter substitution before logging the message of level
450 * DEBUG according to the format outlined above.
451 */
452 public void debug(String format, Object param1, Object param2) {
453 formatAndLog(LOG_LEVEL_DEBUG, format, param1, param2);
454 }
455
456 /**
457 * Perform double parameter substitution before logging the message of level
458 * DEBUG according to the format outlined above.
459 */
460 public void debug(String format, Object... argArray) {
461 formatAndLog(LOG_LEVEL_DEBUG, format, argArray);
462 }
463
464 /** Log a message of level DEBUG, including an exception. */
465 public void debug(String msg, Throwable t) {
466 log(LOG_LEVEL_DEBUG, msg, t);
467 }
468
469 /** Are {@code info} messages currently enabled? */
470 public boolean isInfoEnabled() {
471 return isLevelEnabled(LOG_LEVEL_INFO);
472 }
473
474 /**
475 * A simple implementation which logs messages of level INFO according to
476 * the format outlined above.
477 */
478 public void info(String msg) {
479 log(LOG_LEVEL_INFO, msg, null);
480 }
481
482 /**
483 * Perform single parameter substitution before logging the message of level
484 * INFO according to the format outlined above.
485 */
486 public void info(String format, Object arg) {
487 formatAndLog(LOG_LEVEL_INFO, format, arg, null);
488 }
489
490 /**
491 * Perform double parameter substitution before logging the message of level
492 * INFO according to the format outlined above.
493 */
494 public void info(String format, Object arg1, Object arg2) {
495 formatAndLog(LOG_LEVEL_INFO, format, arg1, arg2);
496 }
497
498 /**
499 * Perform double parameter substitution before logging the message of level
500 * INFO according to the format outlined above.
501 */
502 public void info(String format, Object... argArray) {
503 formatAndLog(LOG_LEVEL_INFO, format, argArray);
504 }
505
506 /** Log a message of level INFO, including an exception. */
507 public void info(String msg, Throwable t) {
508 log(LOG_LEVEL_INFO, msg, t);
509 }
510
511 /** Are {@code warn} messages currently enabled? */
512 public boolean isWarnEnabled() {
513 return isLevelEnabled(LOG_LEVEL_WARN);
514 }
515
516 /**
517 * A simple implementation which always logs messages of level WARN
518 * according to the format outlined above.
519 */
520 public void warn(String msg) {
521 log(LOG_LEVEL_WARN, msg, null);
522 }
523
524 /**
525 * Perform single parameter substitution before logging the message of level
526 * WARN according to the format outlined above.
527 */
528 public void warn(String format, Object arg) {
529 formatAndLog(LOG_LEVEL_WARN, format, arg, null);
530 }
531
532 /**
533 * Perform double parameter substitution before logging the message of level
534 * WARN according to the format outlined above.
535 */
536 public void warn(String format, Object arg1, Object arg2) {
537 formatAndLog(LOG_LEVEL_WARN, format, arg1, arg2);
538 }
539
540 /**
541 * Perform double parameter substitution before logging the message of level
542 * WARN according to the format outlined above.
543 */
544 public void warn(String format, Object... argArray) {
545 formatAndLog(LOG_LEVEL_WARN, format, argArray);
546 }
547
548 /** Log a message of level WARN, including an exception. */
549 public void warn(String msg, Throwable t) {
550 log(LOG_LEVEL_WARN, msg, t);
551 }
552
553 /** Are {@code error} messages currently enabled? */
554 public boolean isErrorEnabled() {
555 return isLevelEnabled(LOG_LEVEL_ERROR);
556 }
557
558 /**
559 * A simple implementation which always logs messages of level ERROR
560 * according to the format outlined above.
561 */
562 public void error(String msg) {
563 log(LOG_LEVEL_ERROR, msg, null);
564 }
565
566 /**
567 * Perform single parameter substitution before logging the message of level
568 * ERROR according to the format outlined above.
569 */
570 public void error(String format, Object arg) {
571 formatAndLog(LOG_LEVEL_ERROR, format, arg, null);
572 }
573
574 /**
575 * Perform double parameter substitution before logging the message of level
576 * ERROR according to the format outlined above.
577 */
578 public void error(String format, Object arg1, Object arg2) {
579 formatAndLog(LOG_LEVEL_ERROR, format, arg1, arg2);
580 }
581
582 /**
583 * Perform double parameter substitution before logging the message of level
584 * ERROR according to the format outlined above.
585 */
586 public void error(String format, Object... argArray) {
587 formatAndLog(LOG_LEVEL_ERROR, format, argArray);
588 }
589
590 /** Log a message of level ERROR, including an exception. */
591 public void error(String msg, Throwable t) {
592 log(LOG_LEVEL_ERROR, msg, t);
593 }
594
595 public void log(LoggingEvent event) {
596 int levelInt = event.getLevel().toInt();
597
598 if (!isLevelEnabled(levelInt)) {
599 return;
600 }
601 FormattingTuple tp = MessageFormatter.arrayFormat(event.getMessage(), event.getArgumentArray(), event.getThrowable());
602 log(levelInt, tp.getMessage(), event.getThrowable());
603 }
604
605 }
0 package org.slf4j.impl;
1
2 import java.io.FileNotFoundException;
3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.io.PrintStream;
6 import java.security.AccessController;
7 import java.security.PrivilegedAction;
8 import java.text.DateFormat;
9 import java.text.SimpleDateFormat;
10 import java.util.Properties;
11
12 import org.slf4j.helpers.Util;
13 import org.slf4j.impl.OutputChoice.OutputChoiceType;
14
15 /**
16 * This class holds configuration values for {@link SimpleLogger}. The
17 * values are computed at runtime. See {@link SimpleLogger} documentation for
18 * more information.
19 *
20 *
21 * @author Ceki G&uuml;lc&uuml;
22 * @author Scott Sanders
23 * @author Rod Waldhoff
24 * @author Robert Burrell Donkin
25 * @author C&eacute;drik LIME
26 *
27 * @since 1.7.25
28 */
29 public class SimpleLoggerConfiguration {
30
31 private static final String CONFIGURATION_FILE = "simplelogger.properties";
32
33 static int DEFAULT_LOG_LEVEL_DEFAULT = SimpleLogger.LOG_LEVEL_INFO;
34 int defaultLogLevel = DEFAULT_LOG_LEVEL_DEFAULT;
35
36 private static final boolean SHOW_DATE_TIME_DEFAULT = false;
37 boolean showDateTime = SHOW_DATE_TIME_DEFAULT;
38
39 private static final String DATE_TIME_FORMAT_STR_DEFAULT = null;
40 private static String dateTimeFormatStr = DATE_TIME_FORMAT_STR_DEFAULT;
41
42 DateFormat dateFormatter = null;
43
44 private static final boolean SHOW_THREAD_NAME_DEFAULT = true;
45 boolean showThreadName = SHOW_THREAD_NAME_DEFAULT;
46
47 final static boolean SHOW_LOG_NAME_DEFAULT = true;
48 boolean showLogName = SHOW_LOG_NAME_DEFAULT;
49
50 private static final boolean SHOW_SHORT_LOG_NAME_DEFAULT = false;
51 boolean showShortLogName = SHOW_SHORT_LOG_NAME_DEFAULT;
52
53 private static final boolean LEVEL_IN_BRACKETS_DEFAULT = false;
54 boolean levelInBrackets = LEVEL_IN_BRACKETS_DEFAULT;
55
56 private static String LOG_FILE_DEFAULT = "System.err";
57 private String logFile = LOG_FILE_DEFAULT;
58 OutputChoice outputChoice = null;
59
60 private static final boolean CACHE_OUTPUT_STREAM_DEFAULT = false;
61 private boolean cacheOutputStream = CACHE_OUTPUT_STREAM_DEFAULT;
62
63 private static final String WARN_LEVELS_STRING_DEFAULT = "WARN";
64 String warnLevelString = WARN_LEVELS_STRING_DEFAULT;
65
66 private final Properties properties = new Properties();
67
68 void init() {
69 loadProperties();
70
71 String defaultLogLevelString = getStringProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, null);
72 if (defaultLogLevelString != null)
73 defaultLogLevel = stringToLevel(defaultLogLevelString);
74
75 showLogName = getBooleanProperty(SimpleLogger.SHOW_LOG_NAME_KEY, SimpleLoggerConfiguration.SHOW_LOG_NAME_DEFAULT);
76 showShortLogName = getBooleanProperty(SimpleLogger.SHOW_SHORT_LOG_NAME_KEY, SHOW_SHORT_LOG_NAME_DEFAULT);
77 showDateTime = getBooleanProperty(SimpleLogger.SHOW_DATE_TIME_KEY, SHOW_DATE_TIME_DEFAULT);
78 showThreadName = getBooleanProperty(SimpleLogger.SHOW_THREAD_NAME_KEY, SHOW_THREAD_NAME_DEFAULT);
79 dateTimeFormatStr = getStringProperty(SimpleLogger.DATE_TIME_FORMAT_KEY, DATE_TIME_FORMAT_STR_DEFAULT);
80 levelInBrackets = getBooleanProperty(SimpleLogger.LEVEL_IN_BRACKETS_KEY, LEVEL_IN_BRACKETS_DEFAULT);
81 warnLevelString = getStringProperty(SimpleLogger.WARN_LEVEL_STRING_KEY, WARN_LEVELS_STRING_DEFAULT);
82
83 logFile = getStringProperty(SimpleLogger.LOG_FILE_KEY, logFile);
84
85 cacheOutputStream = getBooleanProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY, CACHE_OUTPUT_STREAM_DEFAULT);
86 outputChoice = computeOutputChoice(logFile, cacheOutputStream);
87
88 if (dateTimeFormatStr != null) {
89 try {
90 dateFormatter = new SimpleDateFormat(dateTimeFormatStr);
91 } catch (IllegalArgumentException e) {
92 Util.report("Bad date format in " + CONFIGURATION_FILE + "; will output relative time", e);
93 }
94 }
95 }
96
97 private void loadProperties() {
98 // Add props from the resource simplelogger.properties
99 InputStream in = AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
100 public InputStream run() {
101 ClassLoader threadCL = Thread.currentThread().getContextClassLoader();
102 if (threadCL != null) {
103 return threadCL.getResourceAsStream(CONFIGURATION_FILE);
104 } else {
105 return ClassLoader.getSystemResourceAsStream(CONFIGURATION_FILE);
106 }
107 }
108 });
109 if (null != in) {
110 try {
111 properties.load(in);
112 } catch (java.io.IOException e) {
113 // ignored
114 } finally {
115 try {
116 in.close();
117 } catch (java.io.IOException e) {
118 // ignored
119 }
120 }
121 }
122 }
123
124 String getStringProperty(String name, String defaultValue) {
125 String prop = getStringProperty(name);
126 return (prop == null) ? defaultValue : prop;
127 }
128
129 boolean getBooleanProperty(String name, boolean defaultValue) {
130 String prop = getStringProperty(name);
131 return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop);
132 }
133
134 String getStringProperty(String name) {
135 String prop = null;
136 try {
137 prop = System.getProperty(name);
138 } catch (SecurityException e) {
139 ; // Ignore
140 }
141 return (prop == null) ? properties.getProperty(name) : prop;
142 }
143
144 static int stringToLevel(String levelStr) {
145 if ("trace".equalsIgnoreCase(levelStr)) {
146 return SimpleLogger.LOG_LEVEL_TRACE;
147 } else if ("debug".equalsIgnoreCase(levelStr)) {
148 return SimpleLogger.LOG_LEVEL_DEBUG;
149 } else if ("info".equalsIgnoreCase(levelStr)) {
150 return SimpleLogger.LOG_LEVEL_INFO;
151 } else if ("warn".equalsIgnoreCase(levelStr)) {
152 return SimpleLogger.LOG_LEVEL_WARN;
153 } else if ("error".equalsIgnoreCase(levelStr)) {
154 return SimpleLogger.LOG_LEVEL_ERROR;
155 } else if ("off".equalsIgnoreCase(levelStr)) {
156 return SimpleLogger.LOG_LEVEL_OFF;
157 }
158 // assume INFO by default
159 return SimpleLogger.LOG_LEVEL_INFO;
160 }
161
162 private static OutputChoice computeOutputChoice(String logFile, boolean cacheOutputStream) {
163 if ("System.err".equalsIgnoreCase(logFile))
164 if (cacheOutputStream)
165 return new OutputChoice(OutputChoiceType.CACHED_SYS_ERR);
166 else
167 return new OutputChoice(OutputChoiceType.SYS_ERR);
168 else if ("System.out".equalsIgnoreCase(logFile)) {
169 if (cacheOutputStream)
170 return new OutputChoice(OutputChoiceType.CACHED_SYS_OUT);
171 else
172 return new OutputChoice(OutputChoiceType.SYS_OUT);
173 } else {
174 try {
175 FileOutputStream fos = new FileOutputStream(logFile);
176 PrintStream printStream = new PrintStream(fos);
177 return new OutputChoice(printStream);
178 } catch (FileNotFoundException e) {
179 Util.report("Could not open [" + logFile + "]. Defaulting to System.err", e);
180 return new OutputChoice(OutputChoiceType.SYS_ERR);
181 }
182 }
183 }
184
185 }
0 package org.slf4j.impl;
1
2 import java.io.FileNotFoundException;
3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.io.PrintStream;
6 import java.security.AccessController;
7 import java.security.PrivilegedAction;
8 import java.text.DateFormat;
9 import java.text.SimpleDateFormat;
10 import java.util.Properties;
11
12 import org.slf4j.helpers.Util;
13 import org.slf4j.impl.OutputChoice.OutputChoiceType;
14
15 /**
16 * This class holds configuration values for {@link SimpleLogger}. The
17 * values are computed at runtime. See {@link SimpleLogger} documentation for
18 * more information.
19 *
20 *
21 * @author Ceki G&uuml;lc&uuml;
22 * @author Scott Sanders
23 * @author Rod Waldhoff
24 * @author Robert Burrell Donkin
25 * @author C&eacute;drik LIME
26 *
27 * @since 1.7.25
28 */
29 public class SimpleLoggerConfiguration {
30
31 private static final String CONFIGURATION_FILE = "simplelogger.properties";
32
33 static int DEFAULT_LOG_LEVEL_DEFAULT = SimpleLogger.LOG_LEVEL_INFO;
34 int defaultLogLevel = DEFAULT_LOG_LEVEL_DEFAULT;
35
36 private static final boolean SHOW_DATE_TIME_DEFAULT = false;
37 boolean showDateTime = SHOW_DATE_TIME_DEFAULT;
38
39 private static final String DATE_TIME_FORMAT_STR_DEFAULT = null;
40 private static String dateTimeFormatStr = DATE_TIME_FORMAT_STR_DEFAULT;
41
42 DateFormat dateFormatter = null;
43
44 private static final boolean SHOW_THREAD_NAME_DEFAULT = true;
45 boolean showThreadName = SHOW_THREAD_NAME_DEFAULT;
46
47 final static boolean SHOW_LOG_NAME_DEFAULT = true;
48 boolean showLogName = SHOW_LOG_NAME_DEFAULT;
49
50 private static final boolean SHOW_SHORT_LOG_NAME_DEFAULT = false;
51 boolean showShortLogName = SHOW_SHORT_LOG_NAME_DEFAULT;
52
53 private static final boolean LEVEL_IN_BRACKETS_DEFAULT = false;
54 boolean levelInBrackets = LEVEL_IN_BRACKETS_DEFAULT;
55
56 private static String LOG_FILE_DEFAULT = "System.err";
57 private String logFile = LOG_FILE_DEFAULT;
58 OutputChoice outputChoice = null;
59
60 private static final boolean CACHE_OUTPUT_STREAM_DEFAULT = false;
61 private boolean cacheOutputStream = CACHE_OUTPUT_STREAM_DEFAULT;
62
63 private static final String WARN_LEVELS_STRING_DEFAULT = "WARN";
64 String warnLevelString = WARN_LEVELS_STRING_DEFAULT;
65
66 private final Properties properties = new Properties();
67
68 void init() {
69 loadProperties();
70
71 String defaultLogLevelString = getStringProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, null);
72 if (defaultLogLevelString != null)
73 defaultLogLevel = stringToLevel(defaultLogLevelString);
74
75 showLogName = getBooleanProperty(SimpleLogger.SHOW_LOG_NAME_KEY, SimpleLoggerConfiguration.SHOW_LOG_NAME_DEFAULT);
76 showShortLogName = getBooleanProperty(SimpleLogger.SHOW_SHORT_LOG_NAME_KEY, SHOW_SHORT_LOG_NAME_DEFAULT);
77 showDateTime = getBooleanProperty(SimpleLogger.SHOW_DATE_TIME_KEY, SHOW_DATE_TIME_DEFAULT);
78 showThreadName = getBooleanProperty(SimpleLogger.SHOW_THREAD_NAME_KEY, SHOW_THREAD_NAME_DEFAULT);
79 dateTimeFormatStr = getStringProperty(SimpleLogger.DATE_TIME_FORMAT_KEY, DATE_TIME_FORMAT_STR_DEFAULT);
80 levelInBrackets = getBooleanProperty(SimpleLogger.LEVEL_IN_BRACKETS_KEY, LEVEL_IN_BRACKETS_DEFAULT);
81 warnLevelString = getStringProperty(SimpleLogger.WARN_LEVEL_STRING_KEY, WARN_LEVELS_STRING_DEFAULT);
82
83 logFile = getStringProperty(SimpleLogger.LOG_FILE_KEY, logFile);
84
85 cacheOutputStream = getBooleanProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY, CACHE_OUTPUT_STREAM_DEFAULT);
86 outputChoice = computeOutputChoice(logFile, cacheOutputStream);
87
88 if (dateTimeFormatStr != null) {
89 try {
90 dateFormatter = new SimpleDateFormat(dateTimeFormatStr);
91 } catch (IllegalArgumentException e) {
92 Util.report("Bad date format in " + CONFIGURATION_FILE + "; will output relative time", e);
93 }
94 }
95 }
96
97 private void loadProperties() {
98 // Add props from the resource simplelogger.properties
99 InputStream in = AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
100 public InputStream run() {
101 ClassLoader threadCL = Thread.currentThread().getContextClassLoader();
102 if (threadCL != null) {
103 return threadCL.getResourceAsStream(CONFIGURATION_FILE);
104 } else {
105 return ClassLoader.getSystemResourceAsStream(CONFIGURATION_FILE);
106 }
107 }
108 });
109 if (null != in) {
110 try {
111 properties.load(in);
112 } catch (java.io.IOException e) {
113 // ignored
114 } finally {
115 try {
116 in.close();
117 } catch (java.io.IOException e) {
118 // ignored
119 }
120 }
121 }
122 }
123
124 String getStringProperty(String name, String defaultValue) {
125 String prop = getStringProperty(name);
126 return (prop == null) ? defaultValue : prop;
127 }
128
129 boolean getBooleanProperty(String name, boolean defaultValue) {
130 String prop = getStringProperty(name);
131 return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop);
132 }
133
134 String getStringProperty(String name) {
135 String prop = null;
136 try {
137 prop = System.getProperty(name);
138 } catch (SecurityException e) {
139 ; // Ignore
140 }
141 return (prop == null) ? properties.getProperty(name) : prop;
142 }
143
144 static int stringToLevel(String levelStr) {
145 if ("trace".equalsIgnoreCase(levelStr)) {
146 return SimpleLogger.LOG_LEVEL_TRACE;
147 } else if ("debug".equalsIgnoreCase(levelStr)) {
148 return SimpleLogger.LOG_LEVEL_DEBUG;
149 } else if ("info".equalsIgnoreCase(levelStr)) {
150 return SimpleLogger.LOG_LEVEL_INFO;
151 } else if ("warn".equalsIgnoreCase(levelStr)) {
152 return SimpleLogger.LOG_LEVEL_WARN;
153 } else if ("error".equalsIgnoreCase(levelStr)) {
154 return SimpleLogger.LOG_LEVEL_ERROR;
155 } else if ("off".equalsIgnoreCase(levelStr)) {
156 return SimpleLogger.LOG_LEVEL_OFF;
157 }
158 // assume INFO by default
159 return SimpleLogger.LOG_LEVEL_INFO;
160 }
161
162 private static OutputChoice computeOutputChoice(String logFile, boolean cacheOutputStream) {
163 if ("System.err".equalsIgnoreCase(logFile))
164 if (cacheOutputStream)
165 return new OutputChoice(OutputChoiceType.CACHED_SYS_ERR);
166 else
167 return new OutputChoice(OutputChoiceType.SYS_ERR);
168 else if ("System.out".equalsIgnoreCase(logFile)) {
169 if (cacheOutputStream)
170 return new OutputChoice(OutputChoiceType.CACHED_SYS_OUT);
171 else
172 return new OutputChoice(OutputChoiceType.SYS_OUT);
173 } else {
174 try {
175 FileOutputStream fos = new FileOutputStream(logFile);
176 PrintStream printStream = new PrintStream(fos);
177 return new OutputChoice(printStream);
178 } catch (FileNotFoundException e) {
179 Util.report("Could not open [" + logFile + "]. Defaulting to System.err", e);
180 return new OutputChoice(OutputChoiceType.SYS_ERR);
181 }
182 }
183 }
184
185 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.slf4j.Logger;
30 import org.slf4j.ILoggerFactory;
31
32 /**
33 * An implementation of {@link ILoggerFactory} which always returns
34 * {@link SimpleLogger} instances.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class SimpleLoggerFactory implements ILoggerFactory {
39
40 ConcurrentMap<String, Logger> loggerMap;
41
42 public SimpleLoggerFactory() {
43 loggerMap = new ConcurrentHashMap<String, Logger>();
44 SimpleLogger.lazyInit();
45 }
46
47 /**
48 * Return an appropriate {@link SimpleLogger} instance by name.
49 */
50 public Logger getLogger(String name) {
51 Logger simpleLogger = loggerMap.get(name);
52 if (simpleLogger != null) {
53 return simpleLogger;
54 } else {
55 Logger newInstance = new SimpleLogger(name);
56 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
57 return oldInstance == null ? newInstance : oldInstance;
58 }
59 }
60
61 /**
62 * Clear the internal logger cache.
63 *
64 * This method is intended to be called by classes (in the same package) for
65 * testing purposes. This method is internal. It can be modified, renamed or
66 * removed at any time without notice.
67 *
68 * You are strongly discouraged from calling this method in production code.
69 */
70 void reset() {
71 loggerMap.clear();
72 }
73 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.slf4j.Logger;
30 import org.slf4j.ILoggerFactory;
31
32 /**
33 * An implementation of {@link ILoggerFactory} which always returns
34 * {@link SimpleLogger} instances.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class SimpleLoggerFactory implements ILoggerFactory {
39
40 ConcurrentMap<String, Logger> loggerMap;
41
42 public SimpleLoggerFactory() {
43 loggerMap = new ConcurrentHashMap<String, Logger>();
44 SimpleLogger.lazyInit();
45 }
46
47 /**
48 * Return an appropriate {@link SimpleLogger} instance by name.
49 */
50 public Logger getLogger(String name) {
51 Logger simpleLogger = loggerMap.get(name);
52 if (simpleLogger != null) {
53 return simpleLogger;
54 } else {
55 Logger newInstance = new SimpleLogger(name);
56 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
57 return oldInstance == null ? newInstance : oldInstance;
58 }
59 }
60
61 /**
62 * Clear the internal logger cache.
63 *
64 * This method is intended to be called by classes (in the same package) for
65 * testing purposes. This method is internal. It can be modified, renamed or
66 * removed at any time without notice.
67 *
68 * You are strongly discouraged from calling this method in production code.
69 */
70 void reset() {
71 loggerMap.clear();
72 }
73 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public class StaticLoggerBinder implements LoggerFactoryBinder {
38
39 /**
40 * The unique instance of this class.
41 *
42 */
43 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticLoggerBinder singleton
49 */
50 public static final StaticLoggerBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Declare the version of the SLF4J API this implementation is compiled against.
56 * The value of this field is modified with each major release.
57 */
58 // to avoid constant folding by the compiler, this field must *not* be final
59 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
60
61 private static final String loggerFactoryClassStr = SimpleLoggerFactory.class.getName();
62
63 /**
64 * The ILoggerFactory instance returned by the {@link #getLoggerFactory}
65 * method should always be the same object
66 */
67 private final ILoggerFactory loggerFactory;
68
69 private StaticLoggerBinder() {
70 loggerFactory = new SimpleLoggerFactory();
71 }
72
73 public ILoggerFactory getLoggerFactory() {
74 return loggerFactory;
75 }
76
77 public String getLoggerFactoryClassStr() {
78 return loggerFactoryClassStr;
79 }
80 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public class StaticLoggerBinder implements LoggerFactoryBinder {
38
39 /**
40 * The unique instance of this class.
41 *
42 */
43 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticLoggerBinder singleton
49 */
50 public static final StaticLoggerBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Declare the version of the SLF4J API this implementation is compiled against.
56 * The value of this field is modified with each major release.
57 */
58 // to avoid constant folding by the compiler, this field must *not* be final
59 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
60
61 private static final String loggerFactoryClassStr = SimpleLoggerFactory.class.getName();
62
63 /**
64 * The ILoggerFactory instance returned by the {@link #getLoggerFactory}
65 * method should always be the same object
66 */
67 private final ILoggerFactory loggerFactory;
68
69 private StaticLoggerBinder() {
70 loggerFactory = new SimpleLoggerFactory();
71 }
72
73 public ILoggerFactory getLoggerFactory() {
74 return loggerFactory;
75 }
76
77 public String getLoggerFactoryClassStr() {
78 return loggerFactoryClassStr;
79 }
80 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link NOPMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticMDCBinder singleton
48 * @since 1.7.14
49 */
50 public static final StaticMDCBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Currently this method always returns an instance of
56 * {@link StaticMDCBinder}.
57 */
58 public MDCAdapter getMDCA() {
59 return new NOPMDCAdapter();
60 }
61
62 public String getMDCAdapterClassStr() {
63 return NOPMDCAdapter.class.getName();
64 }
65 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link NOPMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticMDCBinder singleton
48 * @since 1.7.14
49 */
50 public static final StaticMDCBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Currently this method always returns an instance of
56 * {@link StaticMDCBinder}.
57 */
58 public MDCAdapter getMDCA() {
59 return new NOPMDCAdapter();
60 }
61
62 public String getMDCAdapterClassStr() {
63 return NOPMDCAdapter.class.getName();
64 }
65 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j.impl;
26
27 import org.slf4j.IMarkerFactory;
28 import org.slf4j.MarkerFactory;
29 import org.slf4j.helpers.BasicMarkerFactory;
30 import org.slf4j.spi.MarkerFactoryBinder;
31
32 /**
33 *
34 * The binding of {@link MarkerFactory} class with an actual instance of
35 * {@link IMarkerFactory} is performed using information returned by this class.
36 *
37 * @author Ceki G&uuml;lc&uuml;
38 */
39 public class StaticMarkerBinder implements MarkerFactoryBinder {
40
41 /**
42 * The unique instance of this class.
43 */
44 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
45
46 final IMarkerFactory markerFactory = new BasicMarkerFactory();
47
48 private StaticMarkerBinder() {
49 }
50
51 /**
52 * Return the singleton of this class.
53 *
54 * @return the StaticMarkerBinder singleton
55 * @since 1.7.14
56 */
57 public static StaticMarkerBinder getSingleton() {
58 return SINGLETON;
59 }
60
61 /**
62 * Currently this method always returns an instance of
63 * {@link BasicMarkerFactory}.
64 */
65 public IMarkerFactory getMarkerFactory() {
66 return markerFactory;
67 }
68
69 /**
70 * Currently, this method returns the class name of
71 * {@link BasicMarkerFactory}.
72 */
73 public String getMarkerFactoryClassStr() {
74 return BasicMarkerFactory.class.getName();
75 }
76
77 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j.impl;
26
27 import org.slf4j.IMarkerFactory;
28 import org.slf4j.MarkerFactory;
29 import org.slf4j.helpers.BasicMarkerFactory;
30 import org.slf4j.spi.MarkerFactoryBinder;
31
32 /**
33 *
34 * The binding of {@link MarkerFactory} class with an actual instance of
35 * {@link IMarkerFactory} is performed using information returned by this class.
36 *
37 * @author Ceki G&uuml;lc&uuml;
38 */
39 public class StaticMarkerBinder implements MarkerFactoryBinder {
40
41 /**
42 * The unique instance of this class.
43 */
44 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
45
46 final IMarkerFactory markerFactory = new BasicMarkerFactory();
47
48 private StaticMarkerBinder() {
49 }
50
51 /**
52 * Return the singleton of this class.
53 *
54 * @return the StaticMarkerBinder singleton
55 * @since 1.7.14
56 */
57 public static StaticMarkerBinder getSingleton() {
58 return SINGLETON;
59 }
60
61 /**
62 * Currently this method always returns an instance of
63 * {@link BasicMarkerFactory}.
64 */
65 public IMarkerFactory getMarkerFactory() {
66 return markerFactory;
67 }
68
69 /**
70 * Currently, this method returns the class name of
71 * {@link BasicMarkerFactory}.
72 */
73 public String getMarkerFactoryClassStr() {
74 return BasicMarkerFactory.class.getName();
75 }
76
77 }
0 Implementation-Title: slf4j-simple
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.simple
3 Bundle-Name: slf4j-simple
4 Bundle-Vendor: SLF4J.ORG
5 Require-Bundle: slf4j.api
6 Bundle-RequiredExecutionEnvironment: J2SE-1.5
7 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
8 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},
9 org.slf4j.spi;version=${parsedVersion.osgiVersion},
10 org.slf4j.helpers;version=${parsedVersion.osgiVersion},
11 org.slf4j.event;version=${parsedVersion.osgiVersion}
0 Implementation-Title: slf4j-simple
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.simple
3 Bundle-Name: slf4j-simple
4 Bundle-Vendor: SLF4J.ORG
5 Require-Bundle: slf4j.api
6 Bundle-RequiredExecutionEnvironment: J2SE-1.5
7 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
8 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},
9 org.slf4j.spi;version=${parsedVersion.osgiVersion},
10 org.slf4j.helpers;version=${parsedVersion.osgiVersion},
11 org.slf4j.event;version=${parsedVersion.osgiVersion}
1212 Fragment-Host: slf4j.api
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
28
29 import java.io.ByteArrayOutputStream;
30 import java.io.PrintStream;
31
32 import org.junit.After;
33 import org.junit.Before;
34 import org.junit.Test;
35
36 /**
37 * Tests that detecting logger name mismatches works and doesn't cause problems
38 * or trigger if disabled.
39 * <p>
40 * This test can't live inside slf4j-api because the NOP Logger doesn't
41 * remember its name.
42 *
43 * @author Alexander Dorokhine
44 * @author Ceki G&uuml;lc&uuml;
45 */
46 public class DetectLoggerNameMismatchTest {
47
48 private static final String MISMATCH_STRING = "Detected logger name mismatch";
49
50 private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
51 private final PrintStream oldErr = System.err;
52
53 @Before
54 public void setUp() {
55 System.setErr(new PrintStream(byteArrayOutputStream));
56 }
57
58 @After
59 public void tearDown() {
60 setTrialEnabled(false);
61 System.setErr(oldErr);
62 }
63
64 /*
65 * Pass in the wrong class to the Logger with the check disabled, and make sure there are no errors.
66 */
67 @Test
68 public void testNoTriggerWithoutProperty() {
69 setTrialEnabled(false);
70 Logger logger = LoggerFactory.getLogger(String.class);
71 assertEquals("java.lang.String", logger.getName());
72 assertMismatchDetected(false);
73 }
74
75 /*
76 * Pass in the wrong class to the Logger with the check enabled, and make sure there ARE errors.
77 */
78 @Test
79 public void testTriggerWithProperty() {
80 setTrialEnabled(true);
81 LoggerFactory.getLogger(String.class);
82 String s = String.valueOf(byteArrayOutputStream);
83 assertMismatchDetected(true);
84 }
85
86 /*
87 * Checks the whole error message to ensure all the names show up correctly.
88 */
89 @Test
90 public void testTriggerWholeMessage() {
91 setTrialEnabled(true);
92 LoggerFactory.getLogger(String.class);
93 boolean success = String.valueOf(byteArrayOutputStream).contains(
94 "Detected logger name mismatch. Given name: \"java.lang.String\"; " + "computed name: \"org.slf4j.DetectLoggerNameMismatchTest\".");
95 assertTrue("Actual value of byteArrayOutputStream: " + String.valueOf(byteArrayOutputStream), success);
96 }
97
98 /*
99 * Checks that there are no errors with the check enabled if the class matches.
100 */
101 @Test
102 public void testPassIfMatch() {
103 setTrialEnabled(true);
104 Logger logger = LoggerFactory.getLogger(DetectLoggerNameMismatchTest.class);
105 assertEquals("org.slf4j.DetectLoggerNameMismatchTest", logger.getName());
106 assertMismatchDetected(false);
107 }
108
109 private void assertMismatchDetected(boolean mismatchDetected) {
110 assertEquals(mismatchDetected, String.valueOf(byteArrayOutputStream).contains(MISMATCH_STRING));
111 }
112
113 @Test
114 public void verifyLoggerDefinedInBaseWithOverridenGetClassMethod() {
115 setTrialEnabled(true);
116 Square square = new Square();
117 assertEquals("org.slf4j.Square", square.logger.getName());
118 assertMismatchDetected(false);
119 }
120
121 private static void setTrialEnabled(boolean enabled) {
122 // The system property is read into a static variable at initialization time
123 // so we cannot just reset the system property to test this feature.
124 // Therefore we set the variable directly.
125 LoggerFactory.DETECT_LOGGER_NAME_MISMATCH = enabled;
126 }
127 }
128
129 // Used for testing that inheritance is ignored by the checker.
130 class ShapeBase {
131 public Logger logger = LoggerFactory.getLogger(getClass());
132 }
133
134 class Square extends ShapeBase {
135 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
28
29 import java.io.ByteArrayOutputStream;
30 import java.io.PrintStream;
31
32 import org.junit.After;
33 import org.junit.Before;
34 import org.junit.Test;
35
36 /**
37 * Tests that detecting logger name mismatches works and doesn't cause problems
38 * or trigger if disabled.
39 * <p>
40 * This test can't live inside slf4j-api because the NOP Logger doesn't
41 * remember its name.
42 *
43 * @author Alexander Dorokhine
44 * @author Ceki G&uuml;lc&uuml;
45 */
46 public class DetectLoggerNameMismatchTest {
47
48 private static final String MISMATCH_STRING = "Detected logger name mismatch";
49
50 private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
51 private final PrintStream oldErr = System.err;
52
53 @Before
54 public void setUp() {
55 System.setErr(new PrintStream(byteArrayOutputStream));
56 }
57
58 @After
59 public void tearDown() {
60 setTrialEnabled(false);
61 System.setErr(oldErr);
62 }
63
64 /*
65 * Pass in the wrong class to the Logger with the check disabled, and make sure there are no errors.
66 */
67 @Test
68 public void testNoTriggerWithoutProperty() {
69 setTrialEnabled(false);
70 Logger logger = LoggerFactory.getLogger(String.class);
71 assertEquals("java.lang.String", logger.getName());
72 assertMismatchDetected(false);
73 }
74
75 /*
76 * Pass in the wrong class to the Logger with the check enabled, and make sure there ARE errors.
77 */
78 @Test
79 public void testTriggerWithProperty() {
80 setTrialEnabled(true);
81 LoggerFactory.getLogger(String.class);
82 String s = String.valueOf(byteArrayOutputStream);
83 assertMismatchDetected(true);
84 }
85
86 /*
87 * Checks the whole error message to ensure all the names show up correctly.
88 */
89 @Test
90 public void testTriggerWholeMessage() {
91 setTrialEnabled(true);
92 LoggerFactory.getLogger(String.class);
93 boolean success = String.valueOf(byteArrayOutputStream).contains(
94 "Detected logger name mismatch. Given name: \"java.lang.String\"; " + "computed name: \"org.slf4j.DetectLoggerNameMismatchTest\".");
95 assertTrue("Actual value of byteArrayOutputStream: " + String.valueOf(byteArrayOutputStream), success);
96 }
97
98 /*
99 * Checks that there are no errors with the check enabled if the class matches.
100 */
101 @Test
102 public void testPassIfMatch() {
103 setTrialEnabled(true);
104 Logger logger = LoggerFactory.getLogger(DetectLoggerNameMismatchTest.class);
105 assertEquals("org.slf4j.DetectLoggerNameMismatchTest", logger.getName());
106 assertMismatchDetected(false);
107 }
108
109 private void assertMismatchDetected(boolean mismatchDetected) {
110 assertEquals(mismatchDetected, String.valueOf(byteArrayOutputStream).contains(MISMATCH_STRING));
111 }
112
113 @Test
114 public void verifyLoggerDefinedInBaseWithOverridenGetClassMethod() {
115 setTrialEnabled(true);
116 Square square = new Square();
117 assertEquals("org.slf4j.Square", square.logger.getName());
118 assertMismatchDetected(false);
119 }
120
121 private static void setTrialEnabled(boolean enabled) {
122 // The system property is read into a static variable at initialization time
123 // so we cannot just reset the system property to test this feature.
124 // Therefore we set the variable directly.
125 LoggerFactory.DETECT_LOGGER_NAME_MISMATCH = enabled;
126 }
127 }
128
129 // Used for testing that inheritance is ignored by the checker.
130 class ShapeBase {
131 public Logger logger = LoggerFactory.getLogger(getClass());
132 }
133
134 class Square extends ShapeBase {
135 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertNull;
27
28 import java.io.PrintStream;
29
30 import org.junit.After;
31 import org.junit.Before;
32 import org.junit.Test;
33
34 /**
35 * Test whether invoking the SLF4J API causes problems or not.
36 *
37 * @author Ceki Gulcu
38 *
39 */
40 public class InvocationTest {
41
42 PrintStream old = System.err;
43
44 @Before
45 public void setUp() throws Exception {
46 System.setErr(new SilentPrintStream(old));
47 }
48
49 @After
50 public void tearDown() throws Exception {
51
52 System.setErr(old);
53 }
54
55 @Test
56 public void test1() {
57 Logger logger = LoggerFactory.getLogger("test1");
58 logger.debug("Hello world.");
59 }
60
61 @Test
62 public void test2() {
63 Integer i1 = new Integer(1);
64 Integer i2 = new Integer(2);
65 Integer i3 = new Integer(3);
66 Exception e = new Exception("This is a test exception.");
67 Logger logger = LoggerFactory.getLogger("test2");
68
69 logger.debug("Hello world 1.");
70 logger.debug("Hello world {}", i1);
71 logger.debug("val={} val={}", i1, i2);
72 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
73
74 logger.debug("Hello world 2", e);
75 logger.info("Hello world 2.");
76
77 logger.warn("Hello world 3.");
78 logger.warn("Hello world 3", e);
79
80 logger.error("Hello world 4.");
81 logger.error("Hello world {}", new Integer(3));
82 logger.error("Hello world 4.", e);
83 }
84
85 // http://jira.qos.ch/browse/SLF4J-69
86 // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=78
87 @Test
88 public void testNullParameter_BUG78() {
89 Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78");
90 String[] parameters = null;
91 String msg = "hello {}";
92 logger.info(msg, (Object[]) parameters);
93 }
94
95 @Test
96 public void testNull() {
97 Logger logger = LoggerFactory.getLogger("testNull");
98 logger.debug(null);
99 logger.info(null);
100 logger.warn(null);
101 logger.error(null);
102
103 Exception e = new Exception("This is a test exception.");
104 logger.debug(null, e);
105 logger.info(null, e);
106 logger.warn(null, e);
107 logger.error(null, e);
108 }
109
110 @Test
111 public void testMarker() {
112 Logger logger = LoggerFactory.getLogger("testMarker");
113 Marker blue = MarkerFactory.getMarker("BLUE");
114 logger.debug(blue, "hello");
115 logger.info(blue, "hello");
116 logger.warn(blue, "hello");
117 logger.error(blue, "hello");
118
119 logger.debug(blue, "hello {}", "world");
120 logger.info(blue, "hello {}", "world");
121 logger.warn(blue, "hello {}", "world");
122 logger.error(blue, "hello {}", "world");
123
124 logger.debug(blue, "hello {} and {} ", "world", "universe");
125 logger.info(blue, "hello {} and {} ", "world", "universe");
126 logger.warn(blue, "hello {} and {} ", "world", "universe");
127 logger.error(blue, "hello {} and {} ", "world", "universe");
128 }
129
130 @Test
131 public void testMDC() {
132 MDC.put("k", "v");
133 assertNull(MDC.get("k"));
134 MDC.remove("k");
135 assertNull(MDC.get("k"));
136 MDC.clear();
137 }
138 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertNull;
27
28 import java.io.PrintStream;
29
30 import org.junit.After;
31 import org.junit.Before;
32 import org.junit.Test;
33
34 /**
35 * Test whether invoking the SLF4J API causes problems or not.
36 *
37 * @author Ceki Gulcu
38 *
39 */
40 public class InvocationTest {
41
42 PrintStream old = System.err;
43
44 @Before
45 public void setUp() throws Exception {
46 System.setErr(new SilentPrintStream(old));
47 }
48
49 @After
50 public void tearDown() throws Exception {
51
52 System.setErr(old);
53 }
54
55 @Test
56 public void test1() {
57 Logger logger = LoggerFactory.getLogger("test1");
58 logger.debug("Hello world.");
59 }
60
61 @Test
62 public void test2() {
63 Integer i1 = new Integer(1);
64 Integer i2 = new Integer(2);
65 Integer i3 = new Integer(3);
66 Exception e = new Exception("This is a test exception.");
67 Logger logger = LoggerFactory.getLogger("test2");
68
69 logger.debug("Hello world 1.");
70 logger.debug("Hello world {}", i1);
71 logger.debug("val={} val={}", i1, i2);
72 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
73
74 logger.debug("Hello world 2", e);
75 logger.info("Hello world 2.");
76
77 logger.warn("Hello world 3.");
78 logger.warn("Hello world 3", e);
79
80 logger.error("Hello world 4.");
81 logger.error("Hello world {}", new Integer(3));
82 logger.error("Hello world 4.", e);
83 }
84
85 // http://jira.qos.ch/browse/SLF4J-69
86 // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=78
87 @Test
88 public void testNullParameter_BUG78() {
89 Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78");
90 String[] parameters = null;
91 String msg = "hello {}";
92 logger.info(msg, (Object[]) parameters);
93 }
94
95 @Test
96 public void testNull() {
97 Logger logger = LoggerFactory.getLogger("testNull");
98 logger.debug(null);
99 logger.info(null);
100 logger.warn(null);
101 logger.error(null);
102
103 Exception e = new Exception("This is a test exception.");
104 logger.debug(null, e);
105 logger.info(null, e);
106 logger.warn(null, e);
107 logger.error(null, e);
108 }
109
110 @Test
111 public void testMarker() {
112 Logger logger = LoggerFactory.getLogger("testMarker");
113 Marker blue = MarkerFactory.getMarker("BLUE");
114 logger.debug(blue, "hello");
115 logger.info(blue, "hello");
116 logger.warn(blue, "hello");
117 logger.error(blue, "hello");
118
119 logger.debug(blue, "hello {}", "world");
120 logger.info(blue, "hello {}", "world");
121 logger.warn(blue, "hello {}", "world");
122 logger.error(blue, "hello {}", "world");
123
124 logger.debug(blue, "hello {} and {} ", "world", "universe");
125 logger.info(blue, "hello {} and {} ", "world", "universe");
126 logger.warn(blue, "hello {} and {} ", "world", "universe");
127 logger.error(blue, "hello {} and {} ", "world", "universe");
128 }
129
130 @Test
131 public void testMDC() {
132 MDC.put("k", "v");
133 assertNull(MDC.get("k"));
134 MDC.remove("k");
135 assertNull(MDC.get("k"));
136 MDC.clear();
137 }
138 }
0 package org.slf4j;
1
2 public class LoggerFactoryFriend {
3 static public void reset() {
4 LoggerFactory.reset();
5 }
6 }
0 package org.slf4j;
1
2 public class LoggerFactoryFriend {
3 static public void reset() {
4 LoggerFactory.reset();
5 }
6 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27
28 public class SilentPrintStream extends PrintStream {
29
30 PrintStream other;
31
32 public SilentPrintStream(PrintStream ps) {
33 super(ps);
34 other = ps;
35 }
36
37 public void print(String s) {
38 }
39
40 public void println(String s) {
41 }
42
43 public void println(Object x) {
44 }
45 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27
28 public class SilentPrintStream extends PrintStream {
29
30 PrintStream other;
31
32 public SilentPrintStream(PrintStream ps) {
33 super(ps);
34 other = ps;
35 }
36
37 public void print(String s) {
38 }
39
40 public void println(String s) {
41 }
42
43 public void println(Object x) {
44 }
45 }
0 /**
1 * Copyright (c) 2004-2016 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.io.PrintStream;
27 import java.util.ArrayList;
28 import java.util.Collections;
29 import java.util.List;
30
31 import org.junit.After;
32 import org.junit.Before;
33 import org.slf4j.LoggerFactoryFriend;
34 import org.slf4j.impl.SimpleLogger;
35
36 public class SimpleLoggerMultithreadedInitializationTest extends MultithreadedInitializationTest {
37 // final static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2;
38 // private final List<Logger> createdLoggers = Collections.synchronizedList(new ArrayList<Logger>());
39 // private final AtomicLong eventCount = new AtomicLong(0);
40 //
41 // private final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1);
42 //
43 // final int diff = new Random().nextInt(10000);
44 static int NUM_LINES_IN_SLF4J_REPLAY_WARNING = 3;
45 private final PrintStream oldErr = System.err;
46 final String loggerName = this.getClass().getName();
47 StringPrintStream sps = new StringPrintStream(oldErr, true);
48
49 @Before
50 public void setup() {
51 System.out.println("THREAD_COUNT=" + THREAD_COUNT);
52 System.setErr(sps);
53 System.setProperty(SimpleLogger.LOG_FILE_KEY, "System.err");
54 LoggerFactoryFriend.reset();
55 }
56
57 @After
58 public void tearDown() throws Exception {
59 LoggerFactoryFriend.reset();
60 System.clearProperty(SimpleLogger.LOG_FILE_KEY);
61 System.setErr(oldErr);
62 }
63
64 @Override
65 protected long getRecordedEventCount() {
66 return sps.stringList.size();
67 };
68
69 @Override
70 protected int extraLogEvents() {
71 return NUM_LINES_IN_SLF4J_REPLAY_WARNING;
72 }
73
74 static class StringPrintStream extends PrintStream {
75
76 public static final String LINE_SEP = System.getProperty("line.separator");
77 PrintStream other;
78 boolean duplicate = false;
79
80 List<String> stringList = Collections.synchronizedList(new ArrayList<String>());
81
82 public StringPrintStream(PrintStream ps, boolean duplicate) {
83 super(ps);
84 other = ps;
85 this.duplicate = duplicate;
86 }
87
88 public StringPrintStream(PrintStream ps) {
89 this(ps, false);
90 }
91
92 public void print(String s) {
93 if (duplicate)
94 other.print(s);
95 stringList.add(s);
96 }
97
98 public void println(String s) {
99 if (duplicate)
100 other.println(s);
101 stringList.add(s);
102 }
103
104 public void println(Object o) {
105 if (duplicate)
106 other.println(o);
107 stringList.add(o.toString());
108 }
109 }
110
111 }
0 /**
1 * Copyright (c) 2004-2016 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.io.PrintStream;
27 import java.util.ArrayList;
28 import java.util.Collections;
29 import java.util.List;
30
31 import org.junit.After;
32 import org.junit.Before;
33 import org.slf4j.LoggerFactoryFriend;
34 import org.slf4j.impl.SimpleLogger;
35
36 public class SimpleLoggerMultithreadedInitializationTest extends MultithreadedInitializationTest {
37 // final static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2;
38 // private final List<Logger> createdLoggers = Collections.synchronizedList(new ArrayList<Logger>());
39 // private final AtomicLong eventCount = new AtomicLong(0);
40 //
41 // private final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1);
42 //
43 // final int diff = new Random().nextInt(10000);
44 static int NUM_LINES_IN_SLF4J_REPLAY_WARNING = 3;
45 private final PrintStream oldErr = System.err;
46 final String loggerName = this.getClass().getName();
47 StringPrintStream sps = new StringPrintStream(oldErr, true);
48
49 @Before
50 public void setup() {
51 System.out.println("THREAD_COUNT=" + THREAD_COUNT);
52 System.setErr(sps);
53 System.setProperty(SimpleLogger.LOG_FILE_KEY, "System.err");
54 LoggerFactoryFriend.reset();
55 }
56
57 @After
58 public void tearDown() throws Exception {
59 LoggerFactoryFriend.reset();
60 System.clearProperty(SimpleLogger.LOG_FILE_KEY);
61 System.setErr(oldErr);
62 }
63
64 @Override
65 protected long getRecordedEventCount() {
66 return sps.stringList.size();
67 };
68
69 @Override
70 protected int extraLogEvents() {
71 return NUM_LINES_IN_SLF4J_REPLAY_WARNING;
72 }
73
74 static class StringPrintStream extends PrintStream {
75
76 public static final String LINE_SEP = System.getProperty("line.separator");
77 PrintStream other;
78 boolean duplicate = false;
79
80 List<String> stringList = Collections.synchronizedList(new ArrayList<String>());
81
82 public StringPrintStream(PrintStream ps, boolean duplicate) {
83 super(ps);
84 other = ps;
85 this.duplicate = duplicate;
86 }
87
88 public StringPrintStream(PrintStream ps) {
89 this(ps, false);
90 }
91
92 public void print(String s) {
93 if (duplicate)
94 other.print(s);
95 stringList.add(s);
96 }
97
98 public void println(String s) {
99 if (duplicate)
100 other.println(s);
101 stringList.add(s);
102 }
103
104 public void println(Object o) {
105 if (duplicate)
106 other.println(o);
107 stringList.add(o.toString());
108 }
109 }
110
111 }
0 /**
1 * Copyright (c) 2004-2012 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertFalse;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.assertTrue;
30
31 import java.io.ByteArrayOutputStream;
32 import java.io.PrintStream;
33
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37
38 public class SimpleLoggerTest {
39
40 String A_KEY = SimpleLogger.LOG_KEY_PREFIX + "a";
41 PrintStream original = System.out;
42 ByteArrayOutputStream bout = new ByteArrayOutputStream();
43 PrintStream replacement = new PrintStream(bout);
44
45 @Before
46 public void before() {
47 System.setProperty(A_KEY, "info");
48 }
49
50 @After
51 public void after() {
52 System.clearProperty(A_KEY);
53 System.clearProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY);
54 System.setErr(original);
55 }
56
57 @Test
58 public void emptyLoggerName() {
59 SimpleLogger simpleLogger = new SimpleLogger("a");
60 assertEquals("info", simpleLogger.recursivelyComputeLevelString());
61 }
62
63 @Test
64 public void offLevel() {
65 System.setProperty(A_KEY, "off");
66 SimpleLogger.init();
67 SimpleLogger simpleLogger = new SimpleLogger("a");
68 assertEquals("off", simpleLogger.recursivelyComputeLevelString());
69 assertFalse(simpleLogger.isErrorEnabled());
70 }
71
72 @Test
73 public void loggerNameWithNoDots_WithLevel() {
74 SimpleLogger.init();
75 SimpleLogger simpleLogger = new SimpleLogger("a");
76
77 assertEquals("info", simpleLogger.recursivelyComputeLevelString());
78 }
79
80 @Test
81 public void loggerNameWithOneDotShouldInheritFromParent() {
82 SimpleLogger simpleLogger = new SimpleLogger("a.b");
83 assertEquals("info", simpleLogger.recursivelyComputeLevelString());
84 }
85
86 @Test
87 public void loggerNameWithNoDots_WithNoSetLevel() {
88 SimpleLogger simpleLogger = new SimpleLogger("x");
89 assertNull(simpleLogger.recursivelyComputeLevelString());
90 }
91
92 @Test
93 public void loggerNameWithOneDot_NoSetLevel() {
94 SimpleLogger simpleLogger = new SimpleLogger("x.y");
95 assertNull(simpleLogger.recursivelyComputeLevelString());
96 }
97
98 @Test
99 public void checkUseOfLastSystemStreamReference() {
100 SimpleLogger.init();
101 SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName());
102
103 System.setErr(replacement);
104 simpleLogger.info("hello");
105 replacement.flush();
106 assertTrue(bout.toString().contains("INFO org.slf4j.impl.SimpleLoggerTest - hello"));
107 }
108
109 @Test
110 public void checkUseOfCachedOutputStream() {
111 System.setErr(replacement);
112 System.setProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY, "true");
113 SimpleLogger.init();
114 SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName());
115 // change reference to original before logging
116 System.setErr(original);
117
118 simpleLogger.info("hello");
119 replacement.flush();
120 assertTrue(bout.toString().contains("INFO org.slf4j.impl.SimpleLoggerTest - hello"));
121 }
122 }
0 /**
1 * Copyright (c) 2004-2012 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertFalse;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.assertTrue;
30
31 import java.io.ByteArrayOutputStream;
32 import java.io.PrintStream;
33
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37
38 public class SimpleLoggerTest {
39
40 String A_KEY = SimpleLogger.LOG_KEY_PREFIX + "a";
41 PrintStream original = System.out;
42 ByteArrayOutputStream bout = new ByteArrayOutputStream();
43 PrintStream replacement = new PrintStream(bout);
44
45 @Before
46 public void before() {
47 System.setProperty(A_KEY, "info");
48 }
49
50 @After
51 public void after() {
52 System.clearProperty(A_KEY);
53 System.clearProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY);
54 System.setErr(original);
55 }
56
57 @Test
58 public void emptyLoggerName() {
59 SimpleLogger simpleLogger = new SimpleLogger("a");
60 assertEquals("info", simpleLogger.recursivelyComputeLevelString());
61 }
62
63 @Test
64 public void offLevel() {
65 System.setProperty(A_KEY, "off");
66 SimpleLogger.init();
67 SimpleLogger simpleLogger = new SimpleLogger("a");
68 assertEquals("off", simpleLogger.recursivelyComputeLevelString());
69 assertFalse(simpleLogger.isErrorEnabled());
70 }
71
72 @Test
73 public void loggerNameWithNoDots_WithLevel() {
74 SimpleLogger.init();
75 SimpleLogger simpleLogger = new SimpleLogger("a");
76
77 assertEquals("info", simpleLogger.recursivelyComputeLevelString());
78 }
79
80 @Test
81 public void loggerNameWithOneDotShouldInheritFromParent() {
82 SimpleLogger simpleLogger = new SimpleLogger("a.b");
83 assertEquals("info", simpleLogger.recursivelyComputeLevelString());
84 }
85
86 @Test
87 public void loggerNameWithNoDots_WithNoSetLevel() {
88 SimpleLogger simpleLogger = new SimpleLogger("x");
89 assertNull(simpleLogger.recursivelyComputeLevelString());
90 }
91
92 @Test
93 public void loggerNameWithOneDot_NoSetLevel() {
94 SimpleLogger simpleLogger = new SimpleLogger("x.y");
95 assertNull(simpleLogger.recursivelyComputeLevelString());
96 }
97
98 @Test
99 public void checkUseOfLastSystemStreamReference() {
100 SimpleLogger.init();
101 SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName());
102
103 System.setErr(replacement);
104 simpleLogger.info("hello");
105 replacement.flush();
106 assertTrue(bout.toString().contains("INFO org.slf4j.impl.SimpleLoggerTest - hello"));
107 }
108
109 @Test
110 public void checkUseOfCachedOutputStream() {
111 System.setErr(replacement);
112 System.setProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY, "true");
113 SimpleLogger.init();
114 SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName());
115 // change reference to original before logging
116 System.setErr(original);
117
118 simpleLogger.info("hello");
119 replacement.flush();
120 assertTrue(bout.toString().contains("INFO org.slf4j.impl.SimpleLoggerTest - hello"));
121 }
122 }
0 # SLF4J's SimpleLogger configuration file
1 # Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.
2
3 # Default logging detail level for all instances of SimpleLogger.
4 # Must be one of ("trace", "debug", "info", "warn", or "error").
5 # If not specified, defaults to "info".
6 #org.slf4j.simpleLogger.defaultLogLevel=info
7
8 # Logging detail level for a SimpleLogger instance named "xxxxx".
9 # Must be one of ("trace", "debug", "info", "warn", or "error").
10 # If not specified, the default logging detail level is used.
11 #org.slf4j.simpleLogger.log.xxxxx=
12
13 # Set to true if you want the current date and time to be included in output messages.
14 # Default is false, and will output the number of milliseconds elapsed since startup.
15 #org.slf4j.simpleLogger.showDateTime=false
16
17 # The date and time format to be used in the output messages.
18 # The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
19 # If the format is not specified or is invalid, the default format is used.
20 # The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
21 #org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
22
23 # Set to true if you want to output the current thread name.
24 # Defaults to true.
25 #org.slf4j.simpleLogger.showThreadName=true
26
27 # Set to true if you want the Logger instance name to be included in output messages.
28 # Defaults to true.
29 #org.slf4j.simpleLogger.showLogName=true
30
31 # Set to true if you want the last component of the name to be included in output messages.
32 # Defaults to false.
33 #org.slf4j.simpleLogger.showShortLogName=false
0 # SLF4J's SimpleLogger configuration file
1 # Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.
2
3 # Default logging detail level for all instances of SimpleLogger.
4 # Must be one of ("trace", "debug", "info", "warn", or "error").
5 # If not specified, defaults to "info".
6 #org.slf4j.simpleLogger.defaultLogLevel=info
7
8 # Logging detail level for a SimpleLogger instance named "xxxxx".
9 # Must be one of ("trace", "debug", "info", "warn", or "error").
10 # If not specified, the default logging detail level is used.
11 #org.slf4j.simpleLogger.log.xxxxx=
12
13 # Set to true if you want the current date and time to be included in output messages.
14 # Default is false, and will output the number of milliseconds elapsed since startup.
15 #org.slf4j.simpleLogger.showDateTime=false
16
17 # The date and time format to be used in the output messages.
18 # The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
19 # If the format is not specified or is invalid, the default format is used.
20 # The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
21 #org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
22
23 # Set to true if you want to output the current thread name.
24 # Defaults to true.
25 #org.slf4j.simpleLogger.showThreadName=true
26
27 # Set to true if you want the Logger instance name to be included in output messages.
28 # Defaults to true.
29 #org.slf4j.simpleLogger.showLogName=true
30
31 # Set to true if you want the last component of the name to be included in output messages.
32 # Defaults to false.
33 #org.slf4j.simpleLogger.showShortLogName=false
0 Copyright (c) 2004-2007 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.25</version>
10 </parent>
11
12 <artifactId>slf4j-site</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J Site</name>
16 <description>SLF4J Site</description>
17 <url>http://www.slf4j.org</url>
18
19 <build>
20 <resources>
21 <resource>
22 <directory>${project.basedir}/src/site/pages</directory>
23 <!-- The {project.basedir}/.. form breaks the eclipse plugin -->
24 <targetPath>../../../target/site</targetPath>
25 <filtering>true</filtering>
26 </resource>
27 <resource>
28 <directory>${project.basedir}/src/main/resources</directory>
29 </resource>
30 </resources>
31 <plugins>
32 <plugin>
33 <groupId>org.apache.maven.plugins</groupId>
34 <artifactId>maven-site-plugin</artifactId>
35 <version>${maven-site-plugin.version}</version>
36 <configuration>
37 <outputDirectory>${project.parent.basedir}/target/site</outputDirectory>
38 </configuration>
39 </plugin>
40 </plugins>
41 </build>
42
43 </project>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.26</version>
10 </parent>
11
12 <artifactId>slf4j-site</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J Site</name>
16 <description>SLF4J Site</description>
17 <url>http://www.slf4j.org</url>
18
19 <build>
20 <resources>
21 <resource>
22 <directory>${project.basedir}/src/site/pages</directory>
23 <!-- The {project.basedir}/.. form breaks the eclipse plugin -->
24 <targetPath>../../../target/site</targetPath>
25 <filtering>true</filtering>
26 </resource>
27 <resource>
28 <directory>${project.basedir}/src/main/resources</directory>
29 </resource>
30 </resources>
31 <plugins>
32
33 <plugin>
34 <groupId>org.apache.maven.plugins</groupId>
35 <artifactId>maven-source-plugin</artifactId>
36 <version>${maven-source-plugin.version}</version>
37 <configuration>
38 <includes>
39 <include>**/META-INF/*</include>
40 </includes>
41
42 <excludes>
43 <exclude>x**</exclude>
44 </excludes>
45 </configuration>
46 <executions>
47 <execution>
48 <phase>package</phase>
49 <goals>
50 <goal>jar</goal>
51 </goals>
52 </execution>
53 </executions>
54 </plugin>
55
56 <plugin>
57 <groupId>org.apache.maven.plugins</groupId>
58 <artifactId>maven-site-plugin</artifactId>
59 <version>${maven-site-plugin.version}</version>
60 <configuration>
61 <outputDirectory>${project.parent.basedir}/target/site</outputDirectory>
62 </configuration>
63 </plugin>
64 </plugins>
65 </build>
66
67 </project>
0 <assembly>
1 <id>dist</id>
2 <formats>
3 <format>zip</format>
4 <format>tar.gz</format>
5 </formats>
6 <fileSets>
7 <!-- Module POMs -->
8 <fileSet>
9 <directory>slf4j-api/</directory>
10 <outputDirectory>slf4j-api/</outputDirectory>
11 <includes>
12 <include>pom.xml</include>
13 </includes>
14 </fileSet>
15
16 <fileSet>
17 <directory>slf4j-jcl/</directory>
18 <outputDirectory>slf4j-jcl/</outputDirectory>
19 <includes>
20 <include>pom.xml</include>
21 </includes>
22 </fileSet>
23
24 <fileSet>
25 <directory>slf4j-jdk14/</directory>
26 <outputDirectory>slf4j-jdk14/</outputDirectory>
27 <includes>
28 <include>pom.xml</include>
29 </includes>
30 </fileSet>
31
32 <fileSet>
33 <directory>slf4j-log4j12/</directory>
34 <outputDirectory>slf4j-log4j12/</outputDirectory>
35 <includes>
36 <include>pom.xml</include>
37 </includes>
38 </fileSet>
39
40 <fileSet>
41 <directory>slf4j-nop/</directory>
42 <outputDirectory>slf4j-nop/</outputDirectory>
43 <includes>
44 <include>pom.xml</include>
45 </includes>
46 </fileSet>
47
48 <fileSet>
49 <directory>slf4j-simple/</directory>
50 <outputDirectory>slf4j-simple/</outputDirectory>
51 <includes>
52 <include>pom.xml</include>
53 </includes>
54 </fileSet>
55
56 <fileSet>
57 <directory>slf4j-android/</directory>
58 <outputDirectory>slf4j-android/</outputDirectory>
59 <includes>
60 <include>pom.xml</include>
61 </includes>
62 </fileSet>
63
64 <fileSet>
65 <directory>slf4j-ext/</directory>
66 <outputDirectory>slf4j-ext/</outputDirectory>
67 <includes>
68 <include>pom.xml</include>
69 </includes>
70 </fileSet>
71
72
73 <fileSet>
74 <directory>jcl104-over-slf4j/</directory>
75 <outputDirectory>jcl104-over-slf4j/</outputDirectory>
76 <includes>
77 <include>pom.xml</include>
78 </includes>
79 </fileSet>
80
81 <fileSet>
82 <directory>jcl-over-slf4j/</directory>
83 <outputDirectory>jcl-over-slf4j/</outputDirectory>
84 <includes>
85 <include>pom.xml</include>
86 </includes>
87 </fileSet>
88
89 <fileSet>
90 <directory>jul-to-slf4j/</directory>
91 <outputDirectory>jul-to-slf4j/</outputDirectory>
92 <includes>
93 <include>pom.xml</include>
94 </includes>
95 </fileSet>
96
97 <fileSet>
98 <directory>log4j-over-slf4j/</directory>
99 <outputDirectory>log4j-over-slf4j/</outputDirectory>
100 <includes><include>pom.xml</include></includes>
101 </fileSet>
102
103 <fileSet>
104 <directory>osgi-over-slf4j/</directory>
105 <outputDirectory>osgi-over-slf4j/</outputDirectory>
106 <includes><include>pom.xml</include></includes>
107 </fileSet>
108
109 <fileSet>
110 <directory>slf4j-site/</directory>
111 <outputDirectory>slf4j-site/</outputDirectory>
112 <includes>
113 <include>pom.xml</include>
114 </includes>
115 </fileSet>
116
117 <fileSet>
118 <directory>slf4j-migrator/</directory>
119 <outputDirectory>slf4j-migrator/</outputDirectory>
120 <includes>
121 <include>pom.xml</include>
122 </includes>
123 </fileSet>
124
125 <fileSet>
126 <directory>integration/</directory>
127 <outputDirectory>integration/</outputDirectory>
128 <includes>
129 <include>pom.xml</include>
130 <include>build.xml</include>
131 <include>osgi-build.xml</include>
132 <include>lib/*</include>
133 </includes>
134 </fileSet>
135
136 <!-- Module Source directories (includes tests) -->
137 <fileSet>
138 <directory>slf4j-api/src/</directory>
139 <outputDirectory>slf4j-api/src/</outputDirectory>
140 <excludes>
141 <exclude>test/output/</exclude>
142 </excludes>
143 </fileSet>
144
145 <fileSet>
146 <directory>slf4j-jcl/src/</directory>
147 <outputDirectory>slf4j-jcl/src/</outputDirectory>
148 </fileSet>
149
150 <fileSet>
151 <directory>slf4j-jdk14/src/</directory>
152 <outputDirectory>slf4j-jdk14/src/</outputDirectory>
153 </fileSet>
154
155 <fileSet>
156 <directory>slf4j-log4j12/src/</directory>
157 <outputDirectory>slf4j-log4j12/src/</outputDirectory>
158 </fileSet>
159 <fileSet>
160 <directory>slf4j-nop/src/</directory>
161 <outputDirectory>slf4j-nop/src/</outputDirectory>
162 </fileSet>
163 <fileSet>
164 <directory>slf4j-simple/src/</directory>
165 <outputDirectory>slf4j-simple/src/</outputDirectory>
166 </fileSet>
167 <fileSet>
168 <directory>slf4j-android/src/</directory>
169 <outputDirectory>slf4j-android/src/</outputDirectory>
170 </fileSet>
171 <fileSet>
172 <directory>slf4j-ext/src/</directory>
173 <outputDirectory>slf4j-ext/src/</outputDirectory>
174 </fileSet>
175 <fileSet>
176 <directory>jcl-over-slf4j/src/</directory>
177 <outputDirectory>jcl-over-slf4j/src/</outputDirectory>
178 </fileSet>
179 <fileSet>
180 <directory>jul-to-slf4j/src/</directory>
181 <outputDirectory>jul-to-slf4j/src/</outputDirectory>
182 </fileSet>
183 <fileSet>
184 <directory>log4j-over-slf4j/src/</directory>
185 <outputDirectory>log4j-over-slf4j/src/</outputDirectory>
186 </fileSet>
187 <fileSet>
188 <directory>osgi-over-slf4j/src/</directory>
189 <outputDirectory>osgi-over-slf4j/src/</outputDirectory>
190 </fileSet>
191 <fileSet>
192 <directory>slf4j-site/src/</directory>
193 <outputDirectory>slf4j-site/src/</outputDirectory>
194 </fileSet>
195 <fileSet>
196 <directory>slf4j-migrator/src/</directory>
197 <outputDirectory>slf4j-migrator/src/</outputDirectory>
198 </fileSet>
199 <fileSet>
200 <directory>integration/src/</directory>
201 <outputDirectory>integration/src/</outputDirectory>
202 </fileSet>
203
204
205 <!-- Module JARs -->
206 <fileSet>
207 <directory>slf4j-api/target/</directory>
208 <outputDirectory>/</outputDirectory>
209 <includes>
210 <include>slf4j-api-${project.version}-sources.jar</include>
211 <include>slf4j-api-${project.version}.jar</include>
212 </includes>
213 </fileSet>
214
215 <fileSet>
216 <directory>slf4j-jcl/target/</directory>
217 <outputDirectory>/</outputDirectory>
218 <includes>
219 <include>slf4j-jcl-${project.version}.jar</include>
220 <include>slf4j-jcl-${project.version}-sources.jar</include>
221 </includes>
222 </fileSet>
223
224 <fileSet>
225 <directory>slf4j-jdk14/target/</directory>
226 <outputDirectory>/</outputDirectory>
227 <includes>
228 <include>slf4j-jdk14-${project.version}-sources.jar</include>
229 <include>slf4j-jdk14-${project.version}.jar</include>
230 </includes>
231 </fileSet>
232
233 <fileSet>
234 <directory>slf4j-log4j12/target/</directory>
235 <outputDirectory>/</outputDirectory>
236 <includes>
237 <include>slf4j-log4j12-${project.version}.jar</include>
238 <include>slf4j-log4j12-${project.version}-sources.jar</include>
239 </includes>
240 </fileSet>
241
242 <fileSet>
243 <directory>slf4j-nop/target/</directory>
244 <outputDirectory>/</outputDirectory>
245 <includes>
246 <include>slf4j-nop-${project.version}.jar</include>
247 <include>slf4j-nop-${project.version}-sources.jar</include>
248 </includes>
249 </fileSet>
250
251 <fileSet>
252 <directory>slf4j-simple/target/</directory>
253 <outputDirectory>/</outputDirectory>
254 <includes>
255 <include>slf4j-simple-${project.version}-sources*.jar</include>
256 <include>slf4j-simple-${project.version}.jar</include>
257 </includes>
258 </fileSet>
259
260 <fileSet>
261 <directory>slf4j-android/target/</directory>
262 <outputDirectory>/</outputDirectory>
263 <includes>
264 <include>slf4j-android-${project.version}-sources*.jar</include>
265 <include>slf4j-android-${project.version}.jar</include>
266 </includes>
267 </fileSet>
268
269
270 <fileSet>
271 <directory>slf4j-ext/target/</directory>
272 <outputDirectory>/</outputDirectory>
273 <includes>
274 <include>slf4j-ext-${project.version}-sources*.jar</include>
275 <include>slf4j-ext-${project.version}.jar</include>
276 </includes>
277 </fileSet>
278
279
280 <fileSet>
281 <directory>jcl-over-slf4j/target/</directory>
282 <outputDirectory>/</outputDirectory>
283 <includes>
284 <include>jcl-over-slf4j-${project.version}-sources.jar</include>
285 <include>jcl-over-slf4j-${project.version}.jar</include>
286 </includes>
287 </fileSet>
288 <fileSet>
289 <directory>jul-to-slf4j/target/</directory>
290 <outputDirectory>/</outputDirectory>
291 <includes>
292 <include>jul-to-slf4j-${project.version}-sources.jar</include>
293 <include>jul-to-slf4j-${project.version}.jar</include>
294 </includes>
295 </fileSet>
296 <fileSet>
297 <directory>log4j-over-slf4j/target/</directory>
298 <outputDirectory>/</outputDirectory>
299 <includes>
300 <include>log4j-over-slf4j-${project.version}.jar</include>
301 <include>log4j-over-slf4j-${project.version}-sources.jar</include>
302 </includes>
303 </fileSet>
304 <fileSet>
305 <directory>osgi-over-slf4j/target/</directory>
306 <outputDirectory>/</outputDirectory>
307 <includes>
308 <include>osgi-over-slf4j-${project.version}.jar</include>
309 <include>osgi-over-slf4j-${project.version}-sources.jar</include>
310 </includes>
311 </fileSet>
312
313 <fileSet>
314 <directory>slf4j-migrator/target/</directory>
315 <outputDirectory>/</outputDirectory>
316 <includes>
317 <include>slf4j-migrator-${project.version}.jar</include>
318 </includes>
319 </fileSet>
320
321 <!-- Website -->
322 <fileSet>
323 <directory>target/site</directory>
324 <outputDirectory>/site</outputDirectory>
325 <excludes>
326 <exclude>dist/*</exclude>
327 </excludes>
328 </fileSet>
329
330 <!-- Parent files -->
331 <fileSet>
332 <includes>
333 <include>src/</include>
334 <include>README*</include>
335 <include>LICENSE*</include>
336 <include>pom.xml</include>
337 </includes>
338 </fileSet>
339 </fileSets>
340
0 <assembly>
1 <id>dist</id>
2 <formats>
3 <format>zip</format>
4 <format>tar.gz</format>
5 </formats>
6 <fileSets>
7 <!-- Module POMs -->
8 <fileSet>
9 <directory>slf4j-api/</directory>
10 <outputDirectory>slf4j-api/</outputDirectory>
11 <includes>
12 <include>pom.xml</include>
13 </includes>
14 </fileSet>
15
16 <fileSet>
17 <directory>slf4j-jcl/</directory>
18 <outputDirectory>slf4j-jcl/</outputDirectory>
19 <includes>
20 <include>pom.xml</include>
21 </includes>
22 </fileSet>
23
24 <fileSet>
25 <directory>slf4j-jdk14/</directory>
26 <outputDirectory>slf4j-jdk14/</outputDirectory>
27 <includes>
28 <include>pom.xml</include>
29 </includes>
30 </fileSet>
31
32 <fileSet>
33 <directory>slf4j-log4j12/</directory>
34 <outputDirectory>slf4j-log4j12/</outputDirectory>
35 <includes>
36 <include>pom.xml</include>
37 </includes>
38 </fileSet>
39
40 <fileSet>
41 <directory>slf4j-nop/</directory>
42 <outputDirectory>slf4j-nop/</outputDirectory>
43 <includes>
44 <include>pom.xml</include>
45 </includes>
46 </fileSet>
47
48 <fileSet>
49 <directory>slf4j-simple/</directory>
50 <outputDirectory>slf4j-simple/</outputDirectory>
51 <includes>
52 <include>pom.xml</include>
53 </includes>
54 </fileSet>
55
56 <fileSet>
57 <directory>slf4j-android/</directory>
58 <outputDirectory>slf4j-android/</outputDirectory>
59 <includes>
60 <include>pom.xml</include>
61 </includes>
62 </fileSet>
63
64 <fileSet>
65 <directory>slf4j-ext/</directory>
66 <outputDirectory>slf4j-ext/</outputDirectory>
67 <includes>
68 <include>pom.xml</include>
69 </includes>
70 </fileSet>
71
72
73 <fileSet>
74 <directory>jcl104-over-slf4j/</directory>
75 <outputDirectory>jcl104-over-slf4j/</outputDirectory>
76 <includes>
77 <include>pom.xml</include>
78 </includes>
79 </fileSet>
80
81 <fileSet>
82 <directory>jcl-over-slf4j/</directory>
83 <outputDirectory>jcl-over-slf4j/</outputDirectory>
84 <includes>
85 <include>pom.xml</include>
86 </includes>
87 </fileSet>
88
89 <fileSet>
90 <directory>jul-to-slf4j/</directory>
91 <outputDirectory>jul-to-slf4j/</outputDirectory>
92 <includes>
93 <include>pom.xml</include>
94 </includes>
95 </fileSet>
96
97 <fileSet>
98 <directory>log4j-over-slf4j/</directory>
99 <outputDirectory>log4j-over-slf4j/</outputDirectory>
100 <includes><include>pom.xml</include></includes>
101 </fileSet>
102
103 <fileSet>
104 <directory>osgi-over-slf4j/</directory>
105 <outputDirectory>osgi-over-slf4j/</outputDirectory>
106 <includes><include>pom.xml</include></includes>
107 </fileSet>
108
109 <fileSet>
110 <directory>slf4j-site/</directory>
111 <outputDirectory>slf4j-site/</outputDirectory>
112 <includes>
113 <include>pom.xml</include>
114 </includes>
115 </fileSet>
116
117 <fileSet>
118 <directory>slf4j-migrator/</directory>
119 <outputDirectory>slf4j-migrator/</outputDirectory>
120 <includes>
121 <include>pom.xml</include>
122 </includes>
123 </fileSet>
124
125 <fileSet>
126 <directory>integration/</directory>
127 <outputDirectory>integration/</outputDirectory>
128 <includes>
129 <include>pom.xml</include>
130 <include>build.xml</include>
131 <include>osgi-build.xml</include>
132 <include>lib/*</include>
133 </includes>
134 </fileSet>
135
136 <!-- Module Source directories (includes tests) -->
137 <fileSet>
138 <directory>slf4j-api/src/</directory>
139 <outputDirectory>slf4j-api/src/</outputDirectory>
140 <excludes>
141 <exclude>test/output/</exclude>
142 </excludes>
143 </fileSet>
144
145 <fileSet>
146 <directory>slf4j-jcl/src/</directory>
147 <outputDirectory>slf4j-jcl/src/</outputDirectory>
148 </fileSet>
149
150 <fileSet>
151 <directory>slf4j-jdk14/src/</directory>
152 <outputDirectory>slf4j-jdk14/src/</outputDirectory>
153 </fileSet>
154
155 <fileSet>
156 <directory>slf4j-log4j12/src/</directory>
157 <outputDirectory>slf4j-log4j12/src/</outputDirectory>
158 </fileSet>
159 <fileSet>
160 <directory>slf4j-nop/src/</directory>
161 <outputDirectory>slf4j-nop/src/</outputDirectory>
162 </fileSet>
163 <fileSet>
164 <directory>slf4j-simple/src/</directory>
165 <outputDirectory>slf4j-simple/src/</outputDirectory>
166 </fileSet>
167 <fileSet>
168 <directory>slf4j-android/src/</directory>
169 <outputDirectory>slf4j-android/src/</outputDirectory>
170 </fileSet>
171 <fileSet>
172 <directory>slf4j-ext/src/</directory>
173 <outputDirectory>slf4j-ext/src/</outputDirectory>
174 </fileSet>
175 <fileSet>
176 <directory>jcl-over-slf4j/src/</directory>
177 <outputDirectory>jcl-over-slf4j/src/</outputDirectory>
178 </fileSet>
179 <fileSet>
180 <directory>jul-to-slf4j/src/</directory>
181 <outputDirectory>jul-to-slf4j/src/</outputDirectory>
182 </fileSet>
183 <fileSet>
184 <directory>log4j-over-slf4j/src/</directory>
185 <outputDirectory>log4j-over-slf4j/src/</outputDirectory>
186 </fileSet>
187 <fileSet>
188 <directory>osgi-over-slf4j/src/</directory>
189 <outputDirectory>osgi-over-slf4j/src/</outputDirectory>
190 </fileSet>
191 <fileSet>
192 <directory>slf4j-site/src/</directory>
193 <outputDirectory>slf4j-site/src/</outputDirectory>
194 </fileSet>
195 <fileSet>
196 <directory>slf4j-migrator/src/</directory>
197 <outputDirectory>slf4j-migrator/src/</outputDirectory>
198 </fileSet>
199 <fileSet>
200 <directory>integration/src/</directory>
201 <outputDirectory>integration/src/</outputDirectory>
202 </fileSet>
203
204
205 <!-- Module JARs -->
206 <fileSet>
207 <directory>slf4j-api/target/</directory>
208 <outputDirectory>/</outputDirectory>
209 <includes>
210 <include>slf4j-api-${project.version}-sources.jar</include>
211 <include>slf4j-api-${project.version}.jar</include>
212 </includes>
213 </fileSet>
214
215 <fileSet>
216 <directory>slf4j-jcl/target/</directory>
217 <outputDirectory>/</outputDirectory>
218 <includes>
219 <include>slf4j-jcl-${project.version}.jar</include>
220 <include>slf4j-jcl-${project.version}-sources.jar</include>
221 </includes>
222 </fileSet>
223
224 <fileSet>
225 <directory>slf4j-jdk14/target/</directory>
226 <outputDirectory>/</outputDirectory>
227 <includes>
228 <include>slf4j-jdk14-${project.version}-sources.jar</include>
229 <include>slf4j-jdk14-${project.version}.jar</include>
230 </includes>
231 </fileSet>
232
233 <fileSet>
234 <directory>slf4j-log4j12/target/</directory>
235 <outputDirectory>/</outputDirectory>
236 <includes>
237 <include>slf4j-log4j12-${project.version}.jar</include>
238 <include>slf4j-log4j12-${project.version}-sources.jar</include>
239 </includes>
240 </fileSet>
241
242 <fileSet>
243 <directory>slf4j-nop/target/</directory>
244 <outputDirectory>/</outputDirectory>
245 <includes>
246 <include>slf4j-nop-${project.version}.jar</include>
247 <include>slf4j-nop-${project.version}-sources.jar</include>
248 </includes>
249 </fileSet>
250
251 <fileSet>
252 <directory>slf4j-simple/target/</directory>
253 <outputDirectory>/</outputDirectory>
254 <includes>
255 <include>slf4j-simple-${project.version}-sources*.jar</include>
256 <include>slf4j-simple-${project.version}.jar</include>
257 </includes>
258 </fileSet>
259
260 <fileSet>
261 <directory>slf4j-android/target/</directory>
262 <outputDirectory>/</outputDirectory>
263 <includes>
264 <include>slf4j-android-${project.version}-sources*.jar</include>
265 <include>slf4j-android-${project.version}.jar</include>
266 </includes>
267 </fileSet>
268
269
270 <fileSet>
271 <directory>slf4j-ext/target/</directory>
272 <outputDirectory>/</outputDirectory>
273 <includes>
274 <include>slf4j-ext-${project.version}-sources*.jar</include>
275 <include>slf4j-ext-${project.version}.jar</include>
276 </includes>
277 </fileSet>
278
279
280 <fileSet>
281 <directory>jcl-over-slf4j/target/</directory>
282 <outputDirectory>/</outputDirectory>
283 <includes>
284 <include>jcl-over-slf4j-${project.version}-sources.jar</include>
285 <include>jcl-over-slf4j-${project.version}.jar</include>
286 </includes>
287 </fileSet>
288 <fileSet>
289 <directory>jul-to-slf4j/target/</directory>
290 <outputDirectory>/</outputDirectory>
291 <includes>
292 <include>jul-to-slf4j-${project.version}-sources.jar</include>
293 <include>jul-to-slf4j-${project.version}.jar</include>
294 </includes>
295 </fileSet>
296 <fileSet>
297 <directory>log4j-over-slf4j/target/</directory>
298 <outputDirectory>/</outputDirectory>
299 <includes>
300 <include>log4j-over-slf4j-${project.version}.jar</include>
301 <include>log4j-over-slf4j-${project.version}-sources.jar</include>
302 </includes>
303 </fileSet>
304 <fileSet>
305 <directory>osgi-over-slf4j/target/</directory>
306 <outputDirectory>/</outputDirectory>
307 <includes>
308 <include>osgi-over-slf4j-${project.version}.jar</include>
309 <include>osgi-over-slf4j-${project.version}-sources.jar</include>
310 </includes>
311 </fileSet>
312
313 <fileSet>
314 <directory>slf4j-migrator/target/</directory>
315 <outputDirectory>/</outputDirectory>
316 <includes>
317 <include>slf4j-migrator-${project.version}.jar</include>
318 </includes>
319 </fileSet>
320
321 <!-- Website -->
322 <fileSet>
323 <directory>target/site</directory>
324 <outputDirectory>/site</outputDirectory>
325 <excludes>
326 <exclude>dist/*</exclude>
327 </excludes>
328 </fileSet>
329
330 <!-- Parent files -->
331 <fileSet>
332 <includes>
333 <include>src/</include>
334 <include>README*</include>
335 <include>LICENSE*</include>
336 <include>pom.xml</include>
337 </includes>
338 </fileSet>
339 </fileSets>
340
341341 </assembly>
0 <additionalHeaders>
1 <javadoc_style>
2 <firstLine>/**</firstLine>
3 <beforeEachLine> * </beforeEachLine>
4 <endLine> */</endLine>
5 <!--<skipLine>packa</skipLine>-->
6 <firstLineDetectionPattern>(\s|\t)*/\*.*$</firstLineDetectionPattern>
7 <lastLineDetectionPattern>.*\*/(\s|\t)*$</lastLineDetectionPattern>
8 </javadoc_style>
0 <additionalHeaders>
1 <javadoc_style>
2 <firstLine>/**</firstLine>
3 <beforeEachLine> * </beforeEachLine>
4 <endLine> */</endLine>
5 <!--<skipLine>packa</skipLine>-->
6 <firstLineDetectionPattern>(\s|\t)*/\*.*$</firstLineDetectionPattern>
7 <lastLineDetectionPattern>.*\*/(\s|\t)*$</lastLineDetectionPattern>
8 </javadoc_style>
99 </additionalHeaders>
0 Copyright (c) 2004-2011 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0 Copyright (c) 2004-2011 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2121
(New empty file)