Skip to content

Commit

Permalink
Merge remote-tracking branch 'play-scala-log4j2-example/2.6.x' into 2…
Browse files Browse the repository at this point in the history
….6.x

* play-scala-log4j2-example/2.6.x: (36 commits)
  Nest play-scala-log4j2-example
  Updated with template-control on 2019-02-13T20:25:39.787Z (#39)
  Upgrade branch 2.6.x using TemplateControl (#37)
  Updated with template-control on 2019-01-17T15:10:57.918Z   /.mergify.yml:     wrote /.mergify.yml
  Updated with template-control on 2019-01-16T12:08:45.730Z   /LICENSE:     wrote /LICENSE   /NOTICE:     wrote /NOTICE   /.mergify.yml:     wrote /.mergify.yml   **build.gradle:         playTest "org.scalatestplus.play:scalatestplus-play_$scalaVersion:3.1.2"
  Updated with template-control on 2019-01-08T14:44:41.516Z (#33)
  Updated with template-control on 2019-01-04T17:13:24.081Z (#28)
  Remove JDK 9 & 10
  Updated with template-control on 2018-11-29T15:50:43.150Z   /.mergify.yml:     wrote /.mergify.yml
  Updated with template-control on 2018-10-08T19:11:41.210Z   **/plugins.sbt:     addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.20")   **build.gradle:     def playVersion = "2.6.20"
  Updated with template-control on 2018-09-11T20:14:50.549Z (#23)
  set log4j2.xml as javaOptions (#20)
  Updated with template-control on 2018-08-20T20:37:13.971Z (#22)
  Updated with template-control on 2018-07-19T01:58:55.708Z (#19)
  Updated with template-control on 2018-07-16T18:38:45.739Z (#18)
  Upgrade branch 2.6.x using TemplateControl (#17)
  Updated with template-control on 2018-05-27T23:54:08.860Z (#16)
  Updated with template-control on 2018-04-06T19:34:58.294Z (#14)
  Updated with template-control on 2018-03-02T18:56:28.624Z (#13)
  Upgrade branch 2.6.x using TemplateControl (#12)
  ...
  • Loading branch information
dwijnand committed Apr 23, 2019
2 parents 5905ae3 + eda37fe commit 3adb946
Show file tree
Hide file tree
Showing 37 changed files with 1,412 additions and 0 deletions.
10 changes: 10 additions & 0 deletions play-scala-log4j2-example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
build
logs
target
/.idea
/.idea_modules
/.classpath
/.gradle
/.project
/.settings
/RUNNING_PID
27 changes: 27 additions & 0 deletions play-scala-log4j2-example/.mergify.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
pull_request_rules:
- name: automatic merge on CI success require review
conditions:
- status-success=Travis CI - Pull Request
- "#approved-reviews-by>=1"
- "#changes-requested-reviews-by=0"
- label!=block-merge
actions:
merge:
method: squash
strict: smart

- name: automatic merge on CI success for TemplateControl
conditions:
- status-success=Travis CI - Pull Request
- label=merge-when-green
- label!=block-merge
actions:
merge:
method: squash
strict: smart

- name: delete branch after merge
conditions:
- merged
actions:
delete_head_branch: {}
50 changes: 50 additions & 0 deletions play-scala-log4j2-example/.travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
language: scala
scala:
- 2.12.8

before_install:
- curl -sL https://github.com/shyiko/jabba/raw/master/install.sh | bash && . ~/.jabba/jabba.sh

env:
global:
- JABBA_HOME=$HOME/.jabba
matrix:
# There is no concise way to specify multi-dimensional build matrix:
# https://github.com/travis-ci/travis-ci/issues/1519
- SCRIPT=scripts/test-sbt [email protected]
- SCRIPT=scripts/test-sbt [email protected]
- SCRIPT=scripts/test-gradle [email protected]
- SCRIPT=scripts/test-gradle [email protected]

# Exclude some combinations from build matrix. See:
# https://docs.travis-ci.com/user/customizing-the-build/#Build-Matrix
matrix:
fast_finish: true
allow_failures:
# Current release of Gradle still does not supports Play 2.7.x releases
# As soon as there is a release of Gradle that fixes that, we can then
# remove this allowed failure.
- env: SCRIPT=scripts/test-gradle [email protected]
- env: SCRIPT=scripts/test-gradle [email protected]
# Java 11 is still not fully supported. It is good that we are already
# testing our sample applications to better discover possible problems
# but we can allow failures here too.
- env: SCRIPT=scripts/test-sbt [email protected]

install:
- $JABBA_HOME/bin/jabba install $TRAVIS_JDK
- unset _JAVA_OPTIONS
- export JAVA_HOME="$JABBA_HOME/jdk/$TRAVIS_JDK" && export PATH="$JAVA_HOME/bin:$PATH" && java -Xmx32m -version

script:
- $SCRIPT

before_cache:
- find $HOME/.ivy2 -name "ivydata-*.properties" -delete
- find $HOME/.sbt -name "*.lock" -delete

cache:
directories:
- "$HOME/.ivy2/cache"
- "$HOME/.gradle/caches"
- "$HOME/.jabba/jdk"
116 changes: 116 additions & 0 deletions play-scala-log4j2-example/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
CC0 1.0 Universal

Statement of Purpose

The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator and
subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").

Certain owners wish to permanently relinquish those rights to a Work for the
purpose of contributing to a commons of creative, cultural and scientific
works ("Commons") that the public can reliably and without fear of later
claims of infringement build upon, modify, incorporate in other works, reuse
and redistribute as freely as possible in any form whatsoever and for any
purposes, including without limitation commercial purposes. These owners may
contribute to the Commons to promote the ideal of a free culture and the
further production of creative, cultural and scientific works, or to gain
reputation or greater distribution for their Work in part through the use and
efforts of others.

For these and/or other purposes and motivations, and without any expectation
of additional consideration or compensation, the person associating CC0 with a
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
and publicly distribute the Work under its terms, with knowledge of his or her
Copyright and Related Rights in the Work and the meaning and intended legal
effect of CC0 on those rights.

1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not limited
to, the following:

i. the right to reproduce, adapt, distribute, perform, display, communicate,
and translate a Work;

ii. moral rights retained by the original author(s) and/or performer(s);

iii. publicity and privacy rights pertaining to a person's image or likeness
depicted in a Work;

iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;

v. rights protecting the extraction, dissemination, use and reuse of data in
a Work;

vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation thereof,
including any amended or successor version of such directive); and

vii. other similar, equivalent or corresponding rights throughout the world
based on applicable law or treaty, and any national implementations thereof.

2. Waiver. To the greatest extent permitted by, but not in contravention of,
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
and Related Rights and associated claims and causes of action, whether now
known or unknown (including existing as well as future claims and causes of
action), in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number of
copies, and (iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
the Waiver for the benefit of each member of the public at large and to the
detriment of Affirmer's heirs and successors, fully intending that such Waiver
shall not be subject to revocation, rescission, cancellation, termination, or
any other legal or equitable action to disrupt the quiet enjoyment of the Work
by the public as contemplated by Affirmer's express Statement of Purpose.

3. Public License Fallback. Should any part of the Waiver for any reason be
judged legally invalid or ineffective under applicable law, then the Waiver
shall be preserved to the maximum extent permitted taking into account
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
is so judged Affirmer hereby grants to each affected person a royalty-free,
non transferable, non sublicensable, non exclusive, irrevocable and
unconditional license to exercise Affirmer's Copyright and Related Rights in
the Work (i) in all territories worldwide, (ii) for the maximum duration
provided by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and (iv) for any
purpose whatsoever, including without limitation commercial, advertising or
promotional purposes (the "License"). The License shall be deemed effective as
of the date CC0 was applied by Affirmer to the Work. Should any part of the
License for any reason be judged legally invalid or ineffective under
applicable law, such partial invalidity or ineffectiveness shall not
invalidate the remainder of the License, and in such case Affirmer hereby
affirms that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any associated claims
and causes of action with respect to the Work, in either case contrary to
Affirmer's express Statement of Purpose.

4. Limitations and Disclaimers.

a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.

b. Affirmer offers the Work as-is and makes no representations or warranties
of any kind concerning the Work, express, implied, statutory or otherwise,
including without limitation warranties of title, merchantability, fitness
for a particular purpose, non infringement, or the absence of latent or
other defects, accuracy, or the present or absence of errors, whether or not
discoverable, all to the greatest extent permissible under applicable law.

c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without limitation
any person's Copyright and Related Rights in the Work. Further, Affirmer
disclaims responsibility for obtaining any necessary consents, permissions
or other rights required for any use of the Work.

d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to this
CC0 or use of the Work.

For more information, please see
<http://creativecommons.org/publicdomain/zero/1.0/>
8 changes: 8 additions & 0 deletions play-scala-log4j2-example/NOTICE
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Written by Lightbend <[email protected]>

To the extent possible under law, the author(s) have dedicated all copyright and
related and neighboring rights to this software to the public domain worldwide.
This software is distributed without any warranty.

You should have received a copy of the CC0 Public Domain Dedication along with
this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
59 changes: 59 additions & 0 deletions play-scala-log4j2-example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Play using Log4j 2

[![Build Status](https://travis-ci.org/playframework/play-scala-log4j2-example.svg?branch=2.6.x)](https://travis-ci.org/playframework/play-scala-log4j2-example)

This is an example project showing a sample Play application that use Log4J 2 instead of using Logback.

Please see [Using a custom logging framework](https://www.playframework.com/documentation/2.6.x/SettingsLogger#Using-a-Custom-Logging-Framework) in the Play documentation for more details.

## Running in Production

This application will package everything correctly when you run `sbt dist` and run the packaged script.

There is an outstanding bug where apparently this didn't work: please add comments to <https://github.com/playframework/playframework/issues/6017> if this doesn't work for you.

## Running in Development

You must define the `log4j.configurationFile` explicitly when the JVM is loaded or `sbt`:

```bash
sbt -Dlog4j.configurationFile=conf/log4j2.xml
```
Or you can set as javaOptions in `build.sbt`:
```bash
javaOptions += "-Dlog4j.configurationFile=conf/log4j2.xml"
```
If you do not run with `log4j.configurationFile` loaded, you will see this error:

```log
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console. Set system property 'log4j2.debug' to show Log4j2 internal initialization logging.
```

After you define the log4j system property, running the application should look like this:

```log
[info] Loading project definition from /Users/player/play-scala-log4j2-example/project
[info] Set current project to play-2.6-log4j2 (in build file:/Users/player/play-scala-log4j2-example/)
No play.logger.configurator found: logging must be configured entirely by the application.
--- (Running the application, auto-reloading is enabled) ---
[INFO ] 2017-12-20 09:41:12.268 [pool-7-thread-2] AkkaHttpServer - Listening for HTTP on /0:0:0:0:0:0:0:0:9000
(Server started, use Enter to stop and go back to the console...)
[info] Compiling 1 Scala source to /Users/player/play-scala-log4j2-example/target/scala-2.12/classes ...
[info] Done compiling.
[INFO ] 2017-12-20 09:41:41.296 [play-dev-mode-akka.actor.default-dispatcher-4] application - ApplicationTimer demo: Starting application at 2017-12-20T11:41:41.295Z.
[INFO ] 2017-12-20 09:41:41.477 [application-akka.actor.default-dispatcher-2] Slf4jLogger - Slf4jLogger started
[WARN ] 2017-12-20 09:41:41.655 [play-dev-mode-akka.actor.default-dispatcher-4] application - Using the following cache for assets
[INFO ] 2017-12-20 09:41:41.670 [play-dev-mode-akka.actor.default-dispatcher-4] Play - Application started (Dev)
````

Note that you will see

```log
No play.logger.configurator found: logging must be configured entirely by the application.
```

when you first start it -- this is a side effect of Play's immediate reload functionality, and will not affect the application itself. You won't see the `play.logger.configurator` warning if you run the Play application in production, because there isn't a different class loader for SBT vs for the Play application.
33 changes: 33 additions & 0 deletions play-scala-log4j2-example/app/Filters.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import javax.inject._
import play.api._
import play.api.http.HttpFilters
import play.api.mvc._

import filters.ExampleFilter

/**
* This class configures filters that run on every request. This
* class is queried by Play to get a list of filters.
*
* Play will automatically use filters from any class called
* `Filters` that is placed the root package. You can load filters
* from a different class by adding a `play.http.filters` setting to
* the `application.conf` configuration file.
*
* @param env Basic environment settings for the current application.
* @param exampleFilter A demonstration filter that adds a header to
* each response.
*/
@Singleton
class Filters @Inject() (
env: Environment,
exampleFilter: ExampleFilter) extends HttpFilters {

override val filters = {
// Use the example filter if we're running development mode. If
// we're running in production or test mode then don't use any
// filters at all.
if (env.mode == Mode.Dev) Seq(exampleFilter) else Seq.empty
}

}
45 changes: 45 additions & 0 deletions play-scala-log4j2-example/app/Log4J2LoggerConfigurator.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import java.io.File
import java.net.URL

import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.core.LoggerContext
import org.apache.logging.log4j.core.config.Configurator
import org.slf4j.ILoggerFactory
import play.api.{Configuration, Environment, LoggerConfigurator, Mode}

class Log4J2LoggerConfigurator extends LoggerConfigurator {

private lazy val factory: ILoggerFactory = org.slf4j.impl.StaticLoggerBinder.getSingleton.getLoggerFactory

override def init(rootPath: File, mode: Mode): Unit = {
val properties = Map("application.home" -> rootPath.getAbsolutePath)
val resourceName = "log4j2.xml"
val resourceUrl = Option(this.getClass.getClassLoader.getResource(resourceName))
configure(properties, resourceUrl)
}

override def shutdown(): Unit = {
val context = LogManager.getContext().asInstanceOf[LoggerContext]
Configurator.shutdown(context)
}

override def configure(env: Environment): Unit = {
val properties = LoggerConfigurator.generateProperties(env, Configuration.empty, Map.empty)
val resourceUrl = env.resource("log4j2.xml")
configure(properties, resourceUrl)
}

override def configure(env: Environment, configuration: Configuration, optionalProperties: Map[String, String]): Unit = {
// LoggerConfigurator.generateProperties enables play.logger.includeConfigProperties=true
val properties = LoggerConfigurator.generateProperties(env, configuration, optionalProperties)
val resourceUrl = env.resource("log4j2.xml")
configure(properties, resourceUrl)
}

override def configure(properties: Map[String, String], config: Option[URL]): Unit = {
val context = LogManager.getContext(false).asInstanceOf[LoggerContext]
context.setConfigLocation(config.get.toURI)
}

override def loggerFactory: ILoggerFactory = factory
}
28 changes: 28 additions & 0 deletions play-scala-log4j2-example/app/Module.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import com.google.inject.AbstractModule
import java.time.Clock

import services.{ApplicationTimer, AtomicCounter, Counter}

/**
* This class is a Guice module that tells Guice how to bind several
* different types. This Guice module is created when the Play
* application starts.
* Play will automatically use any class called `Module` that is in
* the root package. You can create modules in other locations by
* adding `play.modules.enabled` settings to the `application.conf`
* configuration file.
*/
class Module extends AbstractModule {

override def configure() = {
// Use the system clock as the default implementation of Clock
bind(classOf[Clock]).toInstance(Clock.systemDefaultZone)
// Ask Guice to create an instance of ApplicationTimer when the
// application starts.
bind(classOf[ApplicationTimer]).asEagerSingleton
// Set AtomicCounter as the implementation for Counter.
bind(classOf[Counter]).to(classOf[AtomicCounter])
}

}
Loading

0 comments on commit 3adb946

Please sign in to comment.