# ignite-788
Project: http://git-wip-us.apache.org/repos/asf/incubator-ignite/repo Commit: http://git-wip-us.apache.org/repos/asf/incubator-ignite/commit/6894a87b Tree: http://git-wip-us.apache.org/repos/asf/incubator-ignite/tree/6894a87b Diff: http://git-wip-us.apache.org/repos/asf/incubator-ignite/diff/6894a87b Branch: refs/heads/ignite-104 Commit: 6894a87bf66f9de058f184197a6f03b7c01f628f Parents: ae148f1 Author: glutters <miten...@gmail.com> Authored: Sat Jul 18 14:03:47 2015 +0200 Committer: ashutak <ashu...@gridgain.com> Committed: Fri Jul 24 16:58:06 2015 +0300 ---------------------------------------------------------------------- config/ignite-log4j2.xml | 65 +++ config/ignite-log4j2.xml~ | 65 +++ modules/core/src/test/config/log4j2-test.xml | 63 +++ modules/core/src/test/config/log4j2-test.xml~ | 63 +++ modules/log4j2/README.txt | 32 ++ modules/log4j2/licenses/apache-2.0.txt | 202 +++++++ modules/log4j2/pom.xml | 55 ++ modules/log4j2/pom.xml~ | 45 ++ .../ignite/logger/log4j2/Log4J2Logger.java | 544 +++++++++++++++++++ .../ignite/logger/log4j2/Log4J2Logger.java~ | 542 ++++++++++++++++++ .../ignite/logger/log4j2/Log4j2FileAware.java | 35 ++ .../ignite/logger/log4j2/Log4j2FileAware.java~ | 33 ++ .../ignite/logger/log4j2/Log4jFileAware.java~ | 13 + .../ignite/logger/log4j2/package-info.java | 23 + .../log4j2/GridLog4j2CorrectFileNameTest.java | 95 ++++ .../log4j2/GridLog4j2CorrectFileNameTest.java~ | 95 ++++ .../log4j2/GridLog4j2InitializedTest.java | 79 +++ .../log4j2/GridLog4j2InitializedTest.java~ | 79 +++ .../log4j2/GridLog4j2LoggingFileTest.java | 72 +++ .../log4j2/GridLog4j2LoggingFileTest.java~ | 74 +++ .../ignite/logger/log4j2/package-info.java | 22 + .../testsuites/IgniteLog4j2TestSuite.java | 43 ++ pom.xml | 1 + 23 files changed, 2340 insertions(+) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/config/ignite-log4j2.xml ---------------------------------------------------------------------- diff --git a/config/ignite-log4j2.xml b/config/ignite-log4j2.xml new file mode 100644 index 0000000..3c4af7a --- /dev/null +++ b/config/ignite-log4j2.xml @@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + Configuration file for apache ignite 2 + --> +<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" + "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd"> +<Configuration status="debug" strict="true" name="XMLConfigTest" + packages="org.apache.ignite.logger.log4j2"> + <Filter type="ThresholdFilter" level="TRACE"/> + <Appenders> + <Appender type="Console" name="CONSOLE_ERR"> + </Appender> + <Routing name="Routing"> + <Routes pattern="$${ctx:ROUTINGKEY}"> + <Route key="$${ctx:ROUTINGKEY}"> + <RollingFile name="Rolling-default" fileName="work/log/ignite.log" + filePattern="work/log/${date:yyyy-MM}/default-%d{yyyy-MM-dd}-%i.log.gz"> + <PatternLayout> + <pattern>[%d{ABSOLUTE}][%-5p][%t][%c{1}] %m%n</pattern> + </PatternLayout> + <Policies> + <TimeBasedTriggeringPolicy interval="6" modulate="true" /> + <SizeBasedTriggeringPolicy size="10 MB" /> + </Policies> + </RollingFile> + </Route> + <Route> + <RollingFile name="Rolling-${ctx:ROUTINGKEY}" fileName="work/log/ignite-${ctx:ROUTINGKEY}.log" + filePattern="work/log/${date:yyyy-MM}/ignite-${ctx:ROUTINGKEY}-%d{yyyy-MM-dd}-%i.log.gz"> + <PatternLayout> + <pattern>[%d{ABSOLUTE}][%-5p] $${ctx:nodeidmsg}[%t][%c{1}]%msg%n</pattern> + </PatternLayout> + <Policies> + <TimeBasedTriggeringPolicy interval="6" modulate="true" /> + <SizeBasedTriggeringPolicy size="10 MB" /> + </Policies> + </RollingFile> + </Route> + </Routes> + </Routing> + </Appenders> + <Loggers> + <Logger name="org.springframework" level="warn"/> + <Logger name="rg.eclipse.jetty" level="warn"/> + <Logger name="org.eclipse.jetty.util.log" level="warn"/> + <Logger name="org.eclipse.jetty.util.component" level="warn"/> + <Logger name="com.amazonaws" level="warn"/> + <Root level="TRACE"> + <AppenderRef ref="Routing"/> + </Root> + </Loggers> +</Configuration> http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/config/ignite-log4j2.xml~ ---------------------------------------------------------------------- diff --git a/config/ignite-log4j2.xml~ b/config/ignite-log4j2.xml~ new file mode 100644 index 0000000..9abb65d --- /dev/null +++ b/config/ignite-log4j2.xml~ @@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + Configuration file for apache ignite 2 + --> +<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" + "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd"> +<Configuration status="debug" strict="true" name="XMLConfigTest" + packages="org.apache.ignite.logger.log4j2"> + <Filter type="ThresholdFilter" level="TRACE"/> + <Appenders> + <Appender type="Console" name="CONSOLE_ERR"> + </Appender> + <Routing name="Routing"> + <Routes pattern="$${ctx:ROUTINGKEY}"> + <Route key="$${ctx:ROUTINGKEY}"> + <RollingFile name="Rolling-default" fileName="work/log/default.log" + filePattern="work/log/${date:yyyy-MM}/default-%d{yyyy-MM-dd}-%i.log.gz"> + <PatternLayout> + <pattern>[%d{ABSOLUTE}][%-5p][%t][%c{1}] %m%n</pattern> + </PatternLayout> + <Policies> + <TimeBasedTriggeringPolicy interval="6" modulate="true" /> + <SizeBasedTriggeringPolicy size="10 MB" /> + </Policies> + </RollingFile> + </Route> + <Route> + <RollingFile name="Rolling-${ctx:ROUTINGKEY}" fileName="work/log/ignite-${ctx:ROUTINGKEY}.log" + filePattern="work/log/${date:yyyy-MM}/ignite-${ctx:ROUTINGKEY}-%d{yyyy-MM-dd}-%i.log.gz"> + <PatternLayout> + <pattern>[%d{ABSOLUTE}][%-5p] $${ctx:nodeidmsg}[%t][%c{1}]%msg%n</pattern> + </PatternLayout> + <Policies> + <TimeBasedTriggeringPolicy interval="6" modulate="true" /> + <SizeBasedTriggeringPolicy size="10 MB" /> + </Policies> + </RollingFile> + </Route> + </Routes> + </Routing> + </Appenders> + <Loggers> + <Logger name="org.springframework" level="warn"/> + <Logger name="rg.eclipse.jetty" level="warn"/> + <Logger name="org.eclipse.jetty.util.log" level="warn"/> + <Logger name="org.eclipse.jetty.util.component" level="warn"/> + <Logger name="com.amazonaws" level="warn"/> + <Root level="TRACE"> + <AppenderRef ref="Routing"/> + </Root> + </Loggers> +</Configuration> http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/core/src/test/config/log4j2-test.xml ---------------------------------------------------------------------- diff --git a/modules/core/src/test/config/log4j2-test.xml b/modules/core/src/test/config/log4j2-test.xml new file mode 100644 index 0000000..fcfae43 --- /dev/null +++ b/modules/core/src/test/config/log4j2-test.xml @@ -0,0 +1,63 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" + "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd"> +<Configuration status="debug" strict="true" name="XMLConfigTest" + packages="org.apache.ignite.logger.log4j2"> + <Filter type="ThresholdFilter" level="TRACE"/> + <Appenders> + <Appender type="Console" name="CONSOLE_ERR"> + </Appender> + <Routing name="Routing"> + <Routes pattern="$${ctx:ROUTINGKEY}"> + <Route key="$${ctx:ROUTINGKEY}"> + <RollingFile name="Rolling-default" fileName="work/log/ignite.log" + filePattern="work/log/${date:yyyy-MM}/default-%d{yyyy-MM-dd}-%i.log.gz"> + <PatternLayout> + <pattern>[%d{ABSOLUTE}][%-5p][%t][%c{1}] %m%n</pattern> + </PatternLayout> + <Policies> + <TimeBasedTriggeringPolicy interval="6" modulate="true" /> + <SizeBasedTriggeringPolicy size="10 MB" /> + </Policies> + </RollingFile> + </Route> + <Route> + <RollingFile name="Rolling-${ctx:ROUTINGKEY}" fileName="work/log/ignite-${ctx:ROUTINGKEY}.log" + filePattern="work/log/${date:yyyy-MM}/ignite-${ctx:ROUTINGKEY}-%d{yyyy-MM-dd}-%i.log.gz"> + <PatternLayout> + <pattern>[%d{ABSOLUTE}][%-5p] $${ctx:nodeidmsg}[%t][%c{1}]%msg%n</pattern> + </PatternLayout> + <Policies> + <TimeBasedTriggeringPolicy interval="6" modulate="true" /> + <SizeBasedTriggeringPolicy size="10 MB" /> + </Policies> + </RollingFile> + </Route> + </Routes> + </Routing> + </Appenders> + <Loggers> + <Logger name="org.springframework" level="warn"/> + <Logger name="rg.eclipse.jetty" level="warn"/> + <Logger name="org.eclipse.jetty.util.log" level="warn"/> + <Logger name="org.eclipse.jetty.util.component" level="warn"/> + <Logger name="com.amazonaws" level="warn"/> + <Root level="TRACE"> + <AppenderRef ref="Routing"/> + </Root> + </Loggers> +</Configuration> http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/core/src/test/config/log4j2-test.xml~ ---------------------------------------------------------------------- diff --git a/modules/core/src/test/config/log4j2-test.xml~ b/modules/core/src/test/config/log4j2-test.xml~ new file mode 100644 index 0000000..4222b0c --- /dev/null +++ b/modules/core/src/test/config/log4j2-test.xml~ @@ -0,0 +1,63 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" + "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd"> +<Configuration status="debug" strict="true" name="XMLConfigTest" + packages="org.apache.ignite.logger.log4j2"> + <Filter type="ThresholdFilter" level="TRACE"/> + <Appenders> + <Appender type="Console" name="CONSOLE_ERR"> + </Appender> + <Routing name="Routing"> + <Routes pattern="$${ctx:ROUTINGKEY}"> + <Route key="$${ctx:ROUTINGKEY}"> + <RollingFile name="Rolling-default" fileName="work/log/default.log" + filePattern="work/log/${date:yyyy-MM}/default-%d{yyyy-MM-dd}-%i.log.gz"> + <PatternLayout> + <pattern>[%d{ABSOLUTE}][%-5p][%t][%c{1}] %m%n</pattern> + </PatternLayout> + <Policies> + <TimeBasedTriggeringPolicy interval="6" modulate="true" /> + <SizeBasedTriggeringPolicy size="10 MB" /> + </Policies> + </RollingFile> + </Route> + <Route> + <RollingFile name="Rolling-${ctx:ROUTINGKEY}" fileName="work/log/ignite-${ctx:ROUTINGKEY}.log" + filePattern="work/log/${date:yyyy-MM}/ignite-${ctx:ROUTINGKEY}-%d{yyyy-MM-dd}-%i.log.gz"> + <PatternLayout> + <pattern>[%d{ABSOLUTE}][%-5p] $${ctx:nodeidmsg}[%t][%c{1}]%msg%n</pattern> + </PatternLayout> + <Policies> + <TimeBasedTriggeringPolicy interval="6" modulate="true" /> + <SizeBasedTriggeringPolicy size="10 MB" /> + </Policies> + </RollingFile> + </Route> + </Routes> + </Routing> + </Appenders> + <Loggers> + <Logger name="org.springframework" level="warn"/> + <Logger name="rg.eclipse.jetty" level="warn"/> + <Logger name="org.eclipse.jetty.util.log" level="warn"/> + <Logger name="org.eclipse.jetty.util.component" level="warn"/> + <Logger name="com.amazonaws" level="warn"/> + <Root level="TRACE"> + <AppenderRef ref="Routing"/> + </Root> + </Loggers> +</Configuration> http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/README.txt ---------------------------------------------------------------------- diff --git a/modules/log4j2/README.txt b/modules/log4j2/README.txt new file mode 100644 index 0000000..2bf9e79 --- /dev/null +++ b/modules/log4j2/README.txt @@ -0,0 +1,32 @@ +Apache Ignite Log4J2 Module +-------------------------- + +Apache Ignite Log4J2 module provides GridLogger implementation based on Apache Log4J2. + +To enable Log4J2 module when starting a standalone node, move 'optional/ignite-log4j2' folder to +'libs' folder before running 'ignite.{sh|bat}' script. The content of the module folder will +be added to classpath in this case. + +Importing Log4J2 Module In Maven Project +--------------------------------------- + +If you are using Maven to manage dependencies of your project, you can add Log4J2 module +dependency like this (replace '${ignite.version}' with actual Ignite version you are +interested in): + +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 + http://maven.apache.org/xsd/maven-4.0.0.xsd"> + ... + <dependencies> + ... + <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-log4j2</artifactId> + <version>${ignite.version}</version> + </dependency> + ... + </dependencies> + ... +</project> http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/licenses/apache-2.0.txt ---------------------------------------------------------------------- diff --git a/modules/log4j2/licenses/apache-2.0.txt b/modules/log4j2/licenses/apache-2.0.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/modules/log4j2/licenses/apache-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/pom.xml ---------------------------------------------------------------------- diff --git a/modules/log4j2/pom.xml b/modules/log4j2/pom.xml new file mode 100644 index 0000000..f25a31b --- /dev/null +++ b/modules/log4j2/pom.xml @@ -0,0 +1,55 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<!-- + POM file. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-parent</artifactId> + <version>1</version> + <relativePath>../../parent</relativePath> + </parent> + <artifactId>ignite-log4j2</artifactId> + <version>1.0.6-SNAPSHOT</version> + <dependencies> + <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-core</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-api</artifactId> + <version>2.3</version> + </dependency> + <dependency> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-core</artifactId> + <version>2.3</version> + </dependency> + <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-core</artifactId> + <version>${project.version}</version> + <type>test-jar</type> + <scope>test</scope> + </dependency> + </dependencies> +</project> http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/pom.xml~ ---------------------------------------------------------------------- diff --git a/modules/log4j2/pom.xml~ b/modules/log4j2/pom.xml~ new file mode 100644 index 0000000..65912a6 --- /dev/null +++ b/modules/log4j2/pom.xml~ @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<!-- + POM file. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-parent</artifactId> + <version>1</version> + <relativePath>../../parent</relativePath> + </parent> + <artifactId>ignite-log4j2</artifactId> + <version>1.0.6-SNAPSHOT</version> + <dependencies> + <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-core</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-core</artifactId> + <version>${project.version}</version> + <type>test-jar</type> + <scope>test</scope> + </dependency> + </dependencies> +</project> http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4J2Logger.java ---------------------------------------------------------------------- diff --git a/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4J2Logger.java b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4J2Logger.java new file mode 100644 index 0000000..15ef44d --- /dev/null +++ b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4J2Logger.java @@ -0,0 +1,544 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.logger.log4j2; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import org.apache.ignite.IgniteCheckedException; +import org.apache.ignite.IgniteLogger; +import org.apache.ignite.internal.util.GridConcurrentHashSet; +import org.apache.ignite.internal.util.tostring.GridToStringExclude; +import org.apache.ignite.internal.util.typedef.C1; +import org.apache.ignite.internal.util.typedef.internal.A; +import org.apache.ignite.internal.util.typedef.internal.S; +import org.apache.ignite.internal.util.typedef.internal.U; +import org.apache.ignite.lang.IgniteClosure; +import org.apache.ignite.logger.LoggerNodeIdAware; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.ThreadContext; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.appender.ConsoleAppender; +import org.apache.logging.log4j.core.appender.FileAppender; +import org.apache.logging.log4j.core.appender.RollingFileAppender; +import org.apache.logging.log4j.core.config.AppenderRef; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.Configurator; +import org.apache.logging.log4j.core.config.LoggerConfig; +import org.apache.logging.log4j.core.layout.PatternLayout; +import org.jetbrains.annotations.Nullable; + +/** + * Log4j2-based implementation for logging. This logger should be used by + * loaders that have prefer <a target=_new + * href="http://logging.apache.org/log4j/2.x/">log4j2</a>-based logging. + * <p> + * Here is a typical example of configuring log4j logger in Ignite configuration + * file: + * + * <pre name="code" class="xml"> + * <property name="gridLogger"> + * <bean class="org.apache.ignite.grid.logger.log4j.GridLog4J2Logger"> + * <constructor-arg type="java.lang.String" value="config/ignite-log4j2.xml"/> + * </bean> + * </property> + * </pre> + * + * and from your code: + * + * <pre name="code" class="java"> + * IgniteConfiguration cfg = new IgniteConfiguration(); + * ... + * URL xml = U.resolveIgniteUrl("config/custom-log4j.xml"); + * IgniteLogger log = new Log4J2Logger(xml); + * ... + * cfg.setGridLogger(log); + * </pre> + * + * Please take a look at <a target=_new + * href="http://logging.apache.org/log4j/2.x/">Apache Log4j 2.7</a> for + * additional information. + * <p> + * It's recommended to use Ignite logger injection instead of + * using/instantiating logger apacin your task/job code. See + * {@link org.apache.ignite.resources.LoggerResource} annotation about logger + * injection. + * + * Porting for the Log4j2 + * + * @author Gianfranco Murador + */ +public class Log4J2Logger implements IgniteLogger, LoggerNodeIdAware, + Log4j2FileAware { + + /** custom message */ + private static String LOG_MESSAGE = ">>> Local Node [ID: "; + + /** Appenders. */ + private static Collection<FileAppender> fileAppenders = new GridConcurrentHashSet<>(); + + /** */ + private static volatile boolean inited; + + /** */ + private static volatile boolean quiet0; + + /** */ + private static final Object mux = new Object(); + + /** Logger implementation. */ + @GridToStringExclude + private Logger impl; + + /** Path to configuration file. */ + private final String path; + + /** Quiet flag. */ + private final boolean quiet; + + /** Node ID. */ + private UUID nodeId; + + /** + * Creates new logger and automatically detects if root logger already has + * appenders configured. If it does not, the root logger will be configured + * with default appender (analogous to calling + * {@link #Log4J2Logger(boolean) Log4J2Logger(boolean)} with parameter + * {@code true}, otherwise, existing appenders will be used (analogous to + * calling {@link #Log4J2Logger(boolean) Log4J2Logger(boolean)} with + * parameter + */ + public Log4J2Logger() { + this(!isConfigured()); + } + + /** + * Creates new logger with given implementation. + * + * @param impl Log4j implementation to use. + */ + public Log4J2Logger(final Logger impl) { + assert impl != null; + + path = null; + + addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() { + @Override + public Logger apply(Boolean init) { + return impl; + } + }); + + quiet = quiet0; + } + + /** + * Creates new logger. If initialize parameter is {@code true} the Log4j + * logger will be initialized with default console appender and {@code INFO} + * log level. + * + * @param init If {@code true}, then a default console appender with + * following pattern layout will be created: {@code %d ABSOLUTE} + * %-5p [%c{1}] %m%n}. If {@code false}, then no implicit + * initialization will take place, and {@code Log4j} should be + * configured prior to calling this constructor. + */ + public Log4J2Logger(boolean init) { + impl = LogManager.getRootLogger(); + + if (init) { + // Implementation has already been inited, passing NULL. + addConsoleAppenderIfNeeded(Level.INFO, null); + quiet = quiet0; + } else + quiet = true; + path = null; + } + + /** + * Creates new logger with given configuration {@code cfgFile}. + * + * @param cfgFile Log4j configuration XML file. + * @throws IgniteCheckedException Thrown in case logger can't be created. + */ + public Log4J2Logger(File cfgFile) throws IgniteCheckedException { + + final String uri; + + if (cfgFile == null) + throw new IgniteCheckedException( + "Configuration XML file for Log4j must be specified."); + + if (!cfgFile.exists() || cfgFile.isDirectory()) + throw new IgniteCheckedException( + "Log4j configuration path was not found or is a directory: " + + cfgFile); + try { + uri = cfgFile.toURI().toURL().toString(); + } catch (MalformedURLException e) { + throw new IgniteCheckedException(e.toString()); + } + path = cfgFile.getAbsolutePath(); + addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() { + @Override + public Logger apply(Boolean init) { + if (init) { + Configurator.initialize("Log4J2Logger", uri); + } + return LogManager.getRootLogger(); + } + }); + + quiet = quiet0; + } + + /** + * Creates new logger with given configuration {@code path}. + * @param path Path to log4j configuration XML file. + * @throws IgniteCheckedException Thrown in case logger can't be created. + */ + public Log4J2Logger(String path) throws IgniteCheckedException { + if (path == null) + throw new IgniteCheckedException( + "Configuration XML file for Log4j must be specified."); + + this.path = path; + + final URL cfgUrl = U.resolveIgniteUrl(path); + + if (cfgUrl == null) + throw new IgniteCheckedException( + "Log4j configuration path was not found: " + path); + + addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() { + @Override + public Logger apply(Boolean init) { + + if (init) { + Configurator.initialize("Log4J2Logger", cfgUrl.toString()); + } + return LogManager.getRootLogger(); + } + }); + + quiet = quiet0; + } + + /** + * Creates new logger with given configuration {@code cfgUrl}. + * + * @param cfgUrl URL for Log4j configuration XML file. + * @throws IgniteCheckedException Thrown in case logger can't be created. + */ + public Log4J2Logger(final URL cfgUrl) throws IgniteCheckedException { + if (cfgUrl == null) + throw new IgniteCheckedException( + "Configuration XML file for Log4j must be specified."); + path = null; + addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() { + @Override + public Logger apply(Boolean init) { + if (init) { + Configurator.initialize("Log4J2Logger", cfgUrl.toString()); + } + return LogManager.getRootLogger(); + } + }); + + quiet = quiet0; + } + + /** + * Checks if Log4j is already configured within this VM or not + * + * @return {@code True} if log4j was already configured, {@code false} + * otherwise. + */ + public static boolean isConfigured() { + return !(LogManager.getLogger("Log4J2Logger") != null); + } + + /** + * Sets level for internal log4j implementation. + * + * @param level Log level to set. + */ + public void setLevel(Level level) { + LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + Configuration conf = ctx.getConfiguration(); + conf.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(level); + ctx.updateLoggers(conf); + } + + /** {@inheritDoc} */ + @Nullable + @Override + public String fileName() { + org.apache.logging.log4j.core.Logger loggerImpl = (org.apache.logging.log4j.core.Logger) impl; + Collection<Appender> appenders = loggerImpl.getAppenders().values(); + for (Appender a : appenders) { + if (a instanceof FileAppender) { + return ((FileAppender) a).getFileName(); + } + if (a instanceof RollingFileAppender) { + return ((RollingFileAppender) a).getFileName(); + } + } + return null; + } + + /** + * Adds console appender when needed with some default logging settings. + * + * @param logLevel Optional log level. + * @param implInitC Optional log implementation init closure. + */ + private void addConsoleAppenderIfNeeded(@Nullable Level logLevel, + @Nullable IgniteClosure<Boolean, Logger> implInitC) { + if (inited) { + if (implInitC != null) + // Do not init. + impl = implInitC.apply(false); + + return; + } + synchronized (mux) { + if (inited) { + if (implInitC != null) + // Do not init. + impl = implInitC.apply(false); + + return; + } + + if (implInitC != null) + // Init logger impl. + impl = implInitC.apply(true); + + // use the local quite instead of this + boolean quiet = isQuiet(); + + // here added a console logger if not exists, programmatically + // the implementations is more easy with new API + // Log4j2 has always a console logger by default + Logger clog = LogManager.getLogger("CONSOLE"); + if (clog == null) { + + ConsoleAppender console = ConsoleAppender.createAppender( + PatternLayout.createDefaultLayout(), null, "CONSOLE", + "console", null, null); + final LoggerContext ctx = (LoggerContext) new org.apache.logging.log4j.core.LoggerContext( + "console"); + + final Configuration config = ((org.apache.logging.log4j.core.LoggerContext) ctx) + .getConfiguration(); + config.addAppender(console); + AppenderRef ref = AppenderRef.createAppenderRef("console", + logLevel, null); + AppenderRef[] refs = new AppenderRef[] { ref }; + LoggerConfig loggerConfig = LoggerConfig.createLogger("false", + logLevel, "org.apache.logging.log4j", "true", refs, + null, config, null); + loggerConfig.addAppender(console, null, null); + + config.addLogger("org.apache.logging.log4j", loggerConfig); + ((org.apache.logging.log4j.core.LoggerContext) ctx) + .updateLoggers(); + + } + + quiet0 = quiet; + inited = true; + } + } + + /** + * With the new Log4j2 API when can choose the filename in the ThreadContext + * instead of do some hack to setup the file in according to the nodeid. So + * this method is deprecated + */ + @Override + @Deprecated + public void updateFilePath(IgniteClosure<String, String> filePathClos) { + A.notNull(filePathClos, "filePathClos"); + for (FileAppender a : fileAppenders) { + + } + } + + /** + * Adds file appender. + * + * @param a Appender. + */ + public static void addAppender(FileAppender a) { + A.notNull(a, "a"); + fileAppenders.add(a); + } + + /** + * Removes file appender. + * + * @param a Appender. + */ + public static void removeAppender(FileAppender a) { + A.notNull(a, "a"); + fileAppenders.remove(a); + } + + /** {@inheritDoc} */ + @Override + public UUID getNodeId() { + return nodeId; + } + + /** {@inheritDoc} */ + @Override + public void setNodeId(UUID nodeid) { + A.notNull(nodeid, "nodeId"); + String uid = U.id8(nodeid); + + // set up the new thread context + ThreadContext.put("nodeidmsg", LOG_MESSAGE + uid + "]"); + ThreadContext.put("ROUTINGKEY", uid); + + ((org.apache.logging.log4j.core.LoggerContext) LogManager + .getContext(false)).reconfigure(); + this.nodeId = nodeid; + } + + /** {@inheritDoc} */ + @Override + public void debug(String msg) { + if (!impl.isDebugEnabled()) + warning("Logging at DEBUG level without checking if DEBUG level is enabled: " + + msg); + impl.debug(msg); + } + + /** {@inheritDoc} */ + @Override + public void warning(String msg) { + impl.warn(msg); + } + + /** {@inheritDoc} */ + @Override + public void warning(String msg, @Nullable Throwable e) { + impl.warn(msg, e); + } + + /** {@inheritDoc} */ + @Override + public void error(String msg) { + impl.error(msg); + } + + /** {@inheritDoc} */ + @Override + public void error(String msg, @Nullable Throwable e) { + impl.error(msg, e); + } + + /** {@inheritDoc} */ + @Override + public void info(String msg) { + if (!impl.isInfoEnabled()) + warning("Logging at INFO level without checking if INFO level is enabled: " + + msg); + + impl.info(msg); + } + + /** {@inheritDoc} */ + @Override + public boolean isTraceEnabled() { + return impl.isTraceEnabled(); + } + + /** {@inheritDoc} */ + @Override + public boolean isDebugEnabled() { + return impl.isDebugEnabled(); + } + + /** {@inheritDoc} */ + @Override + public boolean isInfoEnabled() { + return impl.isInfoEnabled(); + } + + /** {@inheritDoc} */ + @Override + public boolean isQuiet() { + return !isInfoEnabled() && !isDebugEnabled(); + } + + /** {@inheritDoc} */ + @Override + public String toString() { + return S.toString(Log4J2Logger.class, this); + } + + /** + * Gets files for all registered file appenders. + * + * @return List of files. + */ + public static Collection<String> logFiles() { + Collection<String> res = new ArrayList<String>(fileAppenders.size()); + for (FileAppender a : fileAppenders) + res.add(a.getFileName()); + return res; + } + + /** + * Gets {@link org.apache.ignite.IgniteLogger} wrapper around log4j logger + * for the given category. If category is {@code null}, then root logger is + * returned. If category is an instance of {@link Class} then + * {@code (Class)ctgr).getName()} is used as category name. + * + * @param ctgr {@inheritDoc} + * @return {@link org.apache.ignite.IgniteLogger} wrapper around log4j + * logger. + */ + @Override + public Log4J2Logger getLogger(Object ctgr) { + return new Log4J2Logger( + ctgr == null ? LogManager.getRootLogger() + : ctgr instanceof Class ? LogManager + .getLogger(((Class<?>) ctgr).getName()) + : LogManager.getLogger(ctgr.toString())); + } + + /** {@inheritDoc} */ + @Override + public void trace(String msg) { + if (!impl.isTraceEnabled()) + warning("Logging at TRACE level without checking if TRACE level is enabled: " + + msg); + impl.trace(msg); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4J2Logger.java~ ---------------------------------------------------------------------- diff --git a/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4J2Logger.java~ b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4J2Logger.java~ new file mode 100644 index 0000000..2ac3307 --- /dev/null +++ b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4J2Logger.java~ @@ -0,0 +1,542 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.logger.log4j2; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import org.apache.ignite.IgniteCheckedException; +import org.apache.ignite.IgniteLogger; +import org.apache.ignite.internal.util.GridConcurrentHashSet; +import org.apache.ignite.internal.util.tostring.GridToStringExclude; +import org.apache.ignite.internal.util.typedef.C1; +import org.apache.ignite.internal.util.typedef.internal.A; +import org.apache.ignite.internal.util.typedef.internal.S; +import org.apache.ignite.internal.util.typedef.internal.U; +import org.apache.ignite.lang.IgniteClosure; +import org.apache.ignite.logger.LoggerNodeIdAware; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.ThreadContext; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.appender.ConsoleAppender; +import org.apache.logging.log4j.core.appender.FileAppender; +import org.apache.logging.log4j.core.appender.RollingFileAppender; +import org.apache.logging.log4j.core.config.AppenderRef; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.Configurator; +import org.apache.logging.log4j.core.config.LoggerConfig; +import org.apache.logging.log4j.core.layout.PatternLayout; +import org.jetbrains.annotations.Nullable; + +/** + * Log4j2-based implementation for logging. This logger should be used by + * loaders that have prefer <a target=_new + * href="http://logging.apache.org/log4j/2.x/">log4j2</a>-based logging. + * <p> + * Here is a typical example of configuring log4j logger in Ignite configuration + * file: + * + * <pre name="code" class="xml"> + * <property name="gridLogger"> + * <bean class="org.apache.ignite.grid.logger.log4j.GridLog4J2Logger"> + * <constructor-arg type="java.lang.String" value="config/ignite-log4j2.xml"/> + * </bean> + * </property> + * </pre> + * + * and from your code: + * + * <pre name="code" class="java"> + * IgniteConfiguration cfg = new IgniteConfiguration(); + * ... + * URL xml = U.resolveIgniteUrl("config/custom-log4j.xml"); + * IgniteLogger log = new Log4J2Logger(xml); + * ... + * cfg.setGridLogger(log); + * </pre> + * + * Please take a look at <a target=_new + * href="http://logging.apache.org/log4j/2.x/">Apache Log4j 2.7</a> for + * additional information. + * <p> + * It's recommended to use Ignite logger injection instead of + * using/instantiating logger apacin your task/job code. See + * {@link org.apache.ignite.resources.LoggerResource} annotation about logger + * injection. + * + * Porting for the Log4j2 + * + * @author Gianfranco Murador + */ +public class Log4J2Logger implements IgniteLogger, LoggerNodeIdAware, + Log4j2FileAware { + + /** custom message */ + private static String LOG_MESSAGE = ">>> Local Node [ID: "; + + /** Appenders. */ + private static Collection<FileAppender> fileAppenders = new GridConcurrentHashSet<>(); + + /** */ + private static volatile boolean inited; + + /** */ + private static volatile boolean quiet0; + + /** */ + private static final Object mux = new Object(); + + /** Logger implementation. */ + @GridToStringExclude + private Logger impl; + + /** Path to configuration file. */ + private final String path; + + /** Quiet flag. */ + private final boolean quiet; + + /** Node ID. */ + private UUID nodeId; + + /** + * Creates new logger and automatically detects if root logger already has + * appenders configured. If it does not, the root logger will be configured + * with default appender (analogous to calling {@link #Log4J2Logger(boolean) + * Log4J2Logger(boolean)} with parameter {@code true}, otherwise, existing + * appenders will be used (analogous to calling + * {@link #Log4J2Logger(boolean) Log4J2Logger(boolean)} with parameter + */ + public Log4J2Logger() { + this(!isConfigured()); + } + + /** + * Creates new logger with given implementation. + * @param impl Log4j implementation to use. + */ + public Log4J2Logger(final Logger impl) { + assert impl != null; + + path = null; + + addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() { + @Override + public Logger apply(Boolean init) { + return impl; + } + }); + + quiet = quiet0; + } + + /** + * Creates new logger. If initialize parameter is {@code true} the Log4j + * logger will be initialized with default console appender and {@code INFO} + * log level. + * + * @param init If {@code true}, then a default console appender with + * following pattern layout will be created: {@code %d{ABSOLUTE} %-5p [%c{1}] %m%n}. + * If {@code false}, then no implicit initialization will take place, + * and {@code Log4j} should be configured prior to calling this + * constructor. + */ + public Log4J2Logger(boolean init) { + impl = LogManager.getRootLogger(); + + if (init) { + // Implementation has already been inited, passing NULL. + addConsoleAppenderIfNeeded(Level.INFO, null); + quiet = quiet0; + } else + quiet = true; + path = null; + } + + /** + * Creates new logger with given configuration {@code cfgFile}. + * + * @param cfgFile Log4j configuration XML file. + * @throws IgniteCheckedException Thrown in case logger can't be created. + */ + public Log4J2Logger(File cfgFile) throws IgniteCheckedException { + + final String uri; + + if (cfgFile == null) + throw new IgniteCheckedException( + "Configuration XML file for Log4j must be specified."); + + if (!cfgFile.exists() || cfgFile.isDirectory()) + throw new IgniteCheckedException( + "Log4j configuration path was not found or is a directory: " + + cfgFile); + try { + uri = cfgFile.toURI().toURL().toString(); + } catch (MalformedURLException e) { + throw new IgniteCheckedException(e.toString()); + } + path = cfgFile.getAbsolutePath(); + addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() { + @Override + public Logger apply(Boolean init) { + if (init) { + Configurator.initialize("Log4J2Logger", uri); + } + return LogManager.getRootLogger(); + } + }); + + quiet = quiet0; + } + + /** + * Creates new logger with given configuration {@code path}. + * + * @param path Path to log4j configuration XML file. + * @throws IgniteCheckedException Thrown in case logger can't be created. + */ + public Log4J2Logger(String path) throws IgniteCheckedException { + if (path == null) + throw new IgniteCheckedException( + "Configuration XML file for Log4j must be specified."); + + this.path = path; + + final URL cfgUrl = U.resolveIgniteUrl(path); + + if (cfgUrl == null) + throw new IgniteCheckedException( + "Log4j configuration path was not found: " + path); + + addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() { + @Override + public Logger apply(Boolean init) { + + if (init) { + Configurator.initialize("Log4J2Logger", cfgUrl.toString()); + } + return LogManager.getRootLogger(); + } + }); + + quiet = quiet0; + } + + /** + * Creates new logger with given configuration {@code cfgUrl}. + * + * @param cfgUrl URL for Log4j configuration XML file. + * @throws IgniteCheckedException Thrown in case logger can't be created. + */ + public Log4J2Logger(final URL cfgUrl) throws IgniteCheckedException { + if (cfgUrl == null) + throw new IgniteCheckedException( + "Configuration XML file for Log4j must be specified."); + path = null; + addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() { + @Override + public Logger apply(Boolean init) { + if (init) { + Configurator.initialize("Log4J2Logger", cfgUrl.toString()); + } + return LogManager.getRootLogger(); + } + }); + + quiet = quiet0; + } + + /** + * Checks if Log4j is already configured within this VM or not + * + * @return {@code True} if log4j was already configured, {@code false} + * otherwise. + */ + public static boolean isConfigured() { + return !(LogManager.getLogger("Log4J2Logger") != null); + } + + /** + * Sets level for internal log4j implementation. + * + * @param level Log level to set. + */ + public void setLevel(Level level) { + LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + Configuration conf = ctx.getConfiguration(); + conf.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(level); + ctx.updateLoggers(conf); + } + + /** {@inheritDoc} */ + @Nullable + @Override + public String fileName() { + org.apache.logging.log4j.core.Logger loggerImpl = (org.apache.logging.log4j.core.Logger) impl; + Collection<Appender> appenders = loggerImpl.getAppenders().values(); + for (Appender a : appenders) { + if (a instanceof FileAppender) { + return ((FileAppender) a).getFileName(); + } + if (a instanceof RollingFileAppender) { + return ((RollingFileAppender) a).getFileName(); + } + } + return null; + } + + /** + * Adds console appender when needed with some default logging settings. + * + * @param logLevel Optional log level. + * @param implInitC Optional log implementation init closure. + */ + private void addConsoleAppenderIfNeeded(@Nullable Level logLevel, + @Nullable IgniteClosure<Boolean, Logger> implInitC) { + if (inited) { + if (implInitC != null) + // Do not init. + impl = implInitC.apply(false); + + return; + } + synchronized (mux) { + if (inited) { + if (implInitC != null) + // Do not init. + impl = implInitC.apply(false); + + return; + } + + if (implInitC != null) + // Init logger impl. + impl = implInitC.apply(true); + + // use the local quite instead of this + boolean quiet = isQuiet(); + + // here added a console logger if not exists, programmatically + // the implementations is more easy with new API + // Log4j2 has always a console logger by default + Logger clog = LogManager.getLogger("CONSOLE"); + if (clog == null) { + + ConsoleAppender console = ConsoleAppender.createAppender( + PatternLayout.createDefaultLayout(), null, "CONSOLE", + "console", null, null); + final LoggerContext ctx = (LoggerContext) new org.apache.logging.log4j.core.LoggerContext( + "console"); + + final Configuration config = ((org.apache.logging.log4j.core.LoggerContext) ctx) + .getConfiguration(); + config.addAppender(console); + AppenderRef ref = AppenderRef.createAppenderRef("console", + logLevel, null); + AppenderRef[] refs = new AppenderRef[] { ref }; + LoggerConfig loggerConfig = LoggerConfig.createLogger("false", + logLevel, "org.apache.logging.log4j", "true", refs, + null, config, null); + loggerConfig.addAppender(console, null, null); + + config.addLogger("org.apache.logging.log4j", loggerConfig); + ((org.apache.logging.log4j.core.LoggerContext) ctx) + .updateLoggers(); + + } + + quiet0 = quiet; + inited = true; + } + } + + /** + * With the new Log4j2 API when can choose the filename in the ThreadContext + * instead of do some hack to setup the file in according to the nodeid. + * So this method is deprecated + */ + @Override + @Deprecated + public void updateFilePath(IgniteClosure<String, String> filePathClos) { + A.notNull(filePathClos, "filePathClos"); + for (FileAppender a : fileAppenders) { + + } + } + + /** + * Adds file appender. + * + * @param a Appender. + */ + public static void addAppender(FileAppender a) { + A.notNull(a, "a"); + fileAppenders.add(a); + } + + /** + * Removes file appender. + * + * @param a Appender. + */ + public static void removeAppender(FileAppender a) { + A.notNull(a, "a"); + fileAppenders.remove(a); + } + + /** {@inheritDoc} */ + @Override + public UUID getNodeId() { + return nodeId; + } + + /** {@inheritDoc} */ + @Override + public void setNodeId(UUID nodeid) { + A.notNull(nodeid, "nodeId"); + String uid = U.id8(nodeid); + + // set up the new thread context + ThreadContext.put("nodeidmsg", LOG_MESSAGE + uid + "]"); + ThreadContext.put("ROUTINGKEY", uid); + + ((org.apache.logging.log4j.core.LoggerContext) LogManager + .getContext(false)).reconfigure(); + this.nodeId = nodeid; + } + + /** {@inheritDoc} */ + @Override + public void debug(String msg) { + if (!impl.isDebugEnabled()) + warning("Logging at DEBUG level without checking if DEBUG level is enabled: " + + msg); + impl.debug(msg); + } + + /** {@inheritDoc} */ + @Override + public void warning(String msg) { + impl.warn(msg); + } + + /** {@inheritDoc} */ + @Override + public void warning(String msg, @Nullable Throwable e) { + impl.warn(msg, e); + } + + /** {@inheritDoc} */ + @Override + public void error(String msg) { + impl.error(msg); + } + + /** {@inheritDoc} */ + @Override + public void error(String msg, @Nullable Throwable e) { + impl.error(msg, e); + } + + /** {@inheritDoc} */ + @Override + public void info(String msg) { + if (!impl.isInfoEnabled()) + warning("Logging at INFO level without checking if INFO level is enabled: " + + msg); + + impl.info(msg); + } + + /** {@inheritDoc} */ + @Override + public boolean isTraceEnabled() { + return impl.isTraceEnabled(); + } + + /** {@inheritDoc} */ + @Override + public boolean isDebugEnabled() { + return impl.isDebugEnabled(); + } + + /** {@inheritDoc} */ + @Override + public boolean isInfoEnabled() { + return impl.isInfoEnabled(); + } + + /** {@inheritDoc} */ + @Override + public boolean isQuiet() { + return !isInfoEnabled() && !isDebugEnabled(); + } + + /** {@inheritDoc} */ + @Override + public String toString() { + return S.toString(Log4J2Logger.class, this); + } + + /** + * Gets files for all registered file appenders. + * + * @return List of files. + */ + public static Collection<String> logFiles() { + Collection<String> res = new ArrayList<String>(fileAppenders.size()); + for (FileAppender a : fileAppenders) + res.add(a.getFileName()); + return res; + } + + /** + * Gets {@link org.apache.ignite.IgniteLogger} wrapper around log4j logger for the given + * category. If category is {@code null}, then root logger is returned. If + * category is an instance of {@link Class} then {@code (Class)ctgr).getName()} + * is used as category name. + * + * @param ctgr {@inheritDoc} + * @return {@link org.apache.ignite.IgniteLogger} wrapper around log4j logger. + */ + @Override + public Log4J2Logger getLogger(Object ctgr) { + return new Log4J2Logger( + ctgr == null ? LogManager.getRootLogger() + : ctgr instanceof Class ? LogManager + .getLogger(((Class<?>) ctgr).getName()) + : LogManager.getLogger(ctgr.toString())); + } + + /** {@inheritDoc} */ + @Override + public void trace(String msg) { + if (!impl.isTraceEnabled()) + warning("Logging at TRACE level without checking if TRACE level is enabled: " + + msg); + impl.trace(msg); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4j2FileAware.java ---------------------------------------------------------------------- diff --git a/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4j2FileAware.java b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4j2FileAware.java new file mode 100644 index 0000000..c389e69 --- /dev/null +++ b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4j2FileAware.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.ignite.logger.log4j2; + +import org.apache.ignite.lang.IgniteClosure; + +/** + * Porting for the Log4j2, the interface is useless with the new implementation + * of the module + * + * @author Gianfranco Murador + */ +public interface Log4j2FileAware { + + /** + * Sets closure that later evaluate file path. + * + * @param filePathClos Closure that generates actual file path. + */ + void updateFilePath(IgniteClosure<String, String> filePathClos); +} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4j2FileAware.java~ ---------------------------------------------------------------------- diff --git a/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4j2FileAware.java~ b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4j2FileAware.java~ new file mode 100644 index 0000000..53b3803 --- /dev/null +++ b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4j2FileAware.java~ @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.ignite.logger.log4j2; + +import org.apache.ignite.lang.IgniteClosure; +/** + * Porting for the Log4j2, the interface is useless with the new implementation + * of the module + * @author Gianfranco Murador + */ +public interface Log4j2FileAware { + + /** + * Sets closure that later evaluate file path. + * + * @param filePathClos Closure that generates actual file path. + */ + void updateFilePath(IgniteClosure<String, String> filePathClos); +} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4jFileAware.java~ ---------------------------------------------------------------------- diff --git a/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4jFileAware.java~ b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4jFileAware.java~ new file mode 100644 index 0000000..4405f36 --- /dev/null +++ b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/Log4jFileAware.java~ @@ -0,0 +1,13 @@ +package org.apache.ignite.logger.log4j2; + +import org.apache.ignite.lang.IgniteClosure; + +public interface Log4jFileAware { + + /** + * Sets closure that later evaluate file path. + * + * @param filePathClos Closure that generates actual file path. + */ + void updateFilePath(IgniteClosure<String, String> filePathClos); +} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/package-info.java ---------------------------------------------------------------------- diff --git a/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/package-info.java b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/package-info.java new file mode 100644 index 0000000..642cf8c --- /dev/null +++ b/modules/log4j2/src/main/java/org/apache/ignite/logger/log4j2/package-info.java @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * <!-- Package description. --> + * Contains <b>default</b> Log4j2 implementation for logging. + */ +package org.apache.ignite.logger.log4j2; + http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2CorrectFileNameTest.java ---------------------------------------------------------------------- diff --git a/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2CorrectFileNameTest.java b/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2CorrectFileNameTest.java new file mode 100644 index 0000000..476b3c8 --- /dev/null +++ b/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2CorrectFileNameTest.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.ignite.logger.log4j2; + +import java.io.File; +import junit.framework.TestCase; +import org.apache.ignite.Ignite; +import org.apache.ignite.configuration.IgniteConfiguration; +import org.apache.ignite.internal.util.typedef.G; +import org.apache.ignite.internal.util.typedef.internal.U; +import org.apache.ignite.logger.log4j2.Log4J2Logger; +import org.apache.ignite.testframework.GridTestUtils; +import org.apache.ignite.testframework.junits.common.GridCommonTest; + +/** + * Tests that several grids log to files with correct names. + */ +@GridCommonTest(group = "Logger") +public class GridLog4j2CorrectFileNameTest extends TestCase { + + /** + * Tests correct behaviour in case 2 local nodes are started. + * + * @throws Exception If error occurs. + */ + public void testLogFilesTwoNodes() throws Exception { + checkOneNode(0); + checkOneNode(1); + } + + /** + * Starts the local node and checks for presence of log file. Also checks + * that this is really a log of a started node. + * + * @param id Test-local node ID. + * @throws Exception If error occurred. + */ + private void checkOneNode(int id) throws Exception { + try (Ignite ignite = G.start(getConfiguration("grid" + id))) { + String id8 = U.id8(ignite.cluster().localNode().id()); + String logPath = "work/log/ignite-" + id8 + ".log"; + File logFile = U.resolveIgnitePath(logPath); + assertNotNull("Failed to resolve path: " + logPath, logFile); + assertTrue("Log file does not exist: " + logFile, logFile.exists()); + // We have a row in log with the following content + // con >>> Local node [ID=NodeId ] + String logContent = U.readFileToString(logFile.getAbsolutePath(), + "UTF-8"); + assertTrue( + "Log file does not contain it's node ID: " + logFile, + logContent.contains(">>> Local node [ID=" + + id8.toUpperCase())); + } + } + + /** + * Creates grid configuration. + * + * @param gridName Grid name. + * @return Grid configuration. + * @throws Exception If error occurred. + */ + private static IgniteConfiguration getConfiguration(String gridName) + throws Exception { + IgniteConfiguration cfg = new IgniteConfiguration(); + + + cfg.setGridName(gridName); + // We need of a configuration file passed in + File xml = GridTestUtils + .resolveIgnitePath("modules/core/src/test/config/log4j2-test.xml"); + + assert xml != null; + assert xml.exists() == true; + + cfg.setGridLogger(new Log4J2Logger(xml)); + cfg.setConnectorConfiguration(null); + + return cfg; + } +} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2CorrectFileNameTest.java~ ---------------------------------------------------------------------- diff --git a/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2CorrectFileNameTest.java~ b/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2CorrectFileNameTest.java~ new file mode 100644 index 0000000..074eab2 --- /dev/null +++ b/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2CorrectFileNameTest.java~ @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.ignite.logger.log4j2; + +import java.io.File; +import junit.framework.TestCase; +import org.apache.ignite.Ignite; +import org.apache.ignite.configuration.IgniteConfiguration; +import org.apache.ignite.internal.util.typedef.G; +import org.apache.ignite.internal.util.typedef.internal.U; +import org.apache.ignite.logger.log4j2.Log4J2Logger; +import org.apache.ignite.testframework.GridTestUtils; +import org.apache.ignite.testframework.junits.common.GridCommonTest; + +/** + * Tests that several grids log to files with correct names. + */ +@GridCommonTest(group = "Logger") +public class GridLog4j2CorrectFileNameTest extends TestCase { + + /** + * Tests correct behaviour in case 2 local nodes are started. + * + * @throws Exception If error occurs. + */ + public void testLogFilesTwoNodes() throws Exception { + checkOneNode(0); + checkOneNode(1); + } + + /** + * Starts the local node and checks for presence of log file. Also checks + * that this is really a log of a started node. + * + * @param id Test-local node ID. + * @throws Exception If error occurred. + */ + private void checkOneNode(int id) throws Exception { + try (Ignite ignite = G.start(getConfiguration("grid" + id))) { + String id8 = U.id8(ignite.cluster().localNode().id()); + String logPath = "/home/glutters/Documenti/apache-ignite/commit-patch-788/incubator-ignite/work/log/ignite-" + id8 + ".log"; + File logFile = U.resolveIgnitePath(logPath); + assertNotNull("Failed to resolve path: " + logPath, logFile); + assertTrue("Log file does not exist: " + logFile, logFile.exists()); + // We have a row in log with the following content + // con >>> Local node [ID=NodeId ] + String logContent = U.readFileToString(logFile.getAbsolutePath(), + "UTF-8"); + assertTrue( + "Log file does not contain it's node ID: " + logFile, + logContent.contains(">>> Local node [ID=" + + id8.toUpperCase())); + } + } + + /** + * Creates grid configuration. + * + * @param gridName Grid name. + * @return Grid configuration. + * @throws Exception If error occurred. + */ + private static IgniteConfiguration getConfiguration(String gridName) + throws Exception { + IgniteConfiguration cfg = new IgniteConfiguration(); + + + cfg.setGridName(gridName); + // We need of a configuration file passed in + File xml = GridTestUtils + .resolveIgnitePath("modules/core/src/test/config/log4j2-test.xml"); + + assert xml != null; + assert xml.exists() == true; + + cfg.setGridLogger(new Log4J2Logger(xml)); + cfg.setConnectorConfiguration(null); + + return cfg; + } +} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/6894a87b/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2InitializedTest.java ---------------------------------------------------------------------- diff --git a/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2InitializedTest.java b/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2InitializedTest.java new file mode 100644 index 0000000..3059861 --- /dev/null +++ b/modules/log4j2/src/test/java/org/apache/ignite/logger/log4j2/GridLog4j2InitializedTest.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.logger.log4j2; + +import java.net.URL; +import java.util.UUID; +import junit.framework.TestCase; +import org.apache.ignite.IgniteCheckedException; +import org.apache.ignite.IgniteLogger; +import org.apache.ignite.configuration.IgniteConfiguration; +import org.apache.ignite.internal.util.typedef.internal.U; +import org.apache.ignite.logger.log4j2.Log4J2Logger; +import org.apache.ignite.testframework.junits.common.GridCommonTest; + +/** + * Log4j initialized test. + */ +@GridCommonTest(group = "Logger") +public class GridLog4j2InitializedTest extends TestCase { + + /** + * @throws Exception If failed. + */ + @Override + protected void setUp() throws Exception { + + } + + /** */ + public void testLogInitialize() { + + IgniteConfiguration cfg = new IgniteConfiguration(); + + cfg.setGridName("grid" + 1); + cfg.setNodeId(new UUID(1, 1)); + // cfg.setIgniteHome("/home/glutters/Documenti/apache-ignite/ignite-master/incubator-ignite/"); + + URL xml = U.resolveIgniteUrl("config/ignite-log4j2.xml"); + IgniteLogger log; + try { + + log = new Log4J2Logger(xml); + // log.isQuiet(); + cfg.setGridLogger(log); + } catch (IgniteCheckedException e) { + e.printStackTrace(); + return; + } + + assert log.isInfoEnabled() == true; + + if (log.isDebugEnabled()) + log.debug("This is 'debug' message."); + + log.info("This is 'info' message."); + log.warning("This is 'warning' message."); + log.warning("This is 'warning' message.", new Exception( + "It's a test warning exception")); + log.error("This is 'error' message."); + + assert log.getLogger(GridLog4j2InitializedTest.class.getName()) instanceof Log4J2Logger; + } + +}