Skip to content

Commit 9a5010b

Browse files
committed
Merge pull request jaliss#374 from jeantil/logger
Improve logging behaviour
2 parents c4ed0be + 9c654b6 commit 9a5010b

22 files changed

+111
-94
lines changed

docs/src/manual/source/guide/configuration.md

+9
Original file line numberDiff line numberDiff line change
@@ -249,3 +249,12 @@ A sample usage would look like:
249249
## Clustered environments
250250

251251
SecureSocial uses the Play cache to store values while signing in users via OAuth. If you have more than one server then make sure to use a distributed cache (eg: memcached).
252+
253+
## Logging configuration
254+
255+
All the securesocial loggers are defined using Play's logging API under the "securesocial" root logger. If you want to customize the logging level for a securesocial component all you have to do is add a line for it in you application.conf.
256+
For example adding the following line would set all the securesocial loggers at the debug level:
257+
258+
logger.securesocial=DEBUG
259+
260+
For more information on how to customize logging in Play! you can check the corresponding [documentation](http://www.playframework.com/documentation/2.2.0/SettingsLogger)

module-code/app/securesocial/controllers/LoginPage.scala

+3-4
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,15 @@ import play.api.Play
2222
import Play.current
2323
import providers.UsernamePasswordProvider
2424
import providers.utils.RoutesHelper
25-
import play.Logger
2625

2726

2827
/**
2928
* The Login page controller
3029
*/
3130
object LoginPage extends Controller
3231
{
32+
private val logger = play.api.Logger("securesocial.controllers.LoginPage")
33+
3334
/**
3435
* The property that specifies the page the user is redirected to after logging out.
3536
*/
@@ -43,9 +44,7 @@ object LoginPage extends Controller
4344
val to = ProviderController.landingUrl
4445
if ( SecureSocial.currentUser.isDefined ) {
4546
// if the user is already logged in just redirect to the app
46-
if ( Logger.isDebugEnabled() ) {
47-
Logger.debug("User already logged in, skipping login page. Redirecting to %s".format(to))
48-
}
47+
logger.debug("User already logged in, skipping login page. Redirecting to %s".format(to))
4948
Redirect( to )
5049
} else {
5150
import com.typesafe.plugin._

module-code/app/securesocial/controllers/ProviderController.scala

+6-7
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ package securesocial.controllers
1919
import play.api.mvc._
2020
import play.api.i18n.Messages
2121
import securesocial.core._
22-
import play.api.{Play, Logger}
22+
import play.api.Play
2323
import Play.current
2424
import providers.utils.RoutesHelper
2525
import securesocial.core.LoginEvent
@@ -33,6 +33,7 @@ import play.api.http.HeaderNames
3333
*/
3434
object ProviderController extends Controller with SecureSocial
3535
{
36+
private val logger = play.api.Logger("securesocial.controllers.ProviderController")
3637
/**
3738
* The property that specifies the page the user is redirected to if there is no original URL saved in
3839
* the session.
@@ -116,9 +117,7 @@ object ProviderController extends Controller with SecureSocial
116117
request.user match {
117118
case Some(currentUser) =>
118119
UserService.link(currentUser, user)
119-
if ( Logger.isDebugEnabled ) {
120-
Logger.debug(s"[securesocial] linked $currentUser to $user")
121-
}
120+
logger.debug(s"[securesocial] linked $currentUser to $user")
122121
// improve this, I'm duplicating part of the code in completeAuthentication
123122
Redirect(toUrl(modifiedSession)).withSession(modifiedSession-
124123
SecureSocial.OriginalUrlKey -
@@ -135,7 +134,7 @@ object ProviderController extends Controller with SecureSocial
135134
}
136135

137136
case other: Throwable => {
138-
Logger.error("Unable to log user in. An exception was thrown", other)
137+
logger.error("Unable to log user in. An exception was thrown", other)
139138
Redirect(RoutesHelper.login()).flashing("error" -> Messages("securesocial.login.errorLoggingIn"))
140139
}
141140
}
@@ -145,8 +144,8 @@ object ProviderController extends Controller with SecureSocial
145144
}
146145

147146
def completeAuthentication(user: Identity, session: Session)(implicit request: RequestHeader): SimpleResult = {
148-
if ( Logger.isDebugEnabled ) {
149-
Logger.debug("[securesocial] user logged in : [" + user + "]")
147+
if ( logger.isDebugEnabled ) {
148+
logger.debug("[securesocial] user logged in : [" + user + "]")
150149
}
151150
val withSession = Events.fire(new LoginEvent(user)).getOrElse(session)
152151
Authenticator.create(user) match {

module-code/app/securesocial/controllers/Registration.scala

+5-8
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import play.api.mvc.{RequestHeader, Result, Action, Controller}
2121
import play.api.data._
2222
import play.api.data.Forms._
2323
import play.api.data.validation.Constraints._
24-
import play.api.{Play, Logger}
24+
import play.api.Play
2525
import securesocial.core.providers.UsernamePasswordProvider
2626
import securesocial.core._
2727
import com.typesafe.plugin._
@@ -40,6 +40,7 @@ import scala.language.reflectiveCalls
4040
*
4141
*/
4242
object Registration extends Controller {
43+
private val logger = play.api.Logger("securesocial.controllers.Registration")
4344

4445
val providerId = UsernamePasswordProvider.UsernamePassword
4546
val UserNameAlreadyTaken = "securesocial.signup.userNameAlreadyTaken"
@@ -190,9 +191,7 @@ object Registration extends Controller {
190191
*/
191192
def signUp(token: String) = Action { implicit request =>
192193
if (registrationEnabled) {
193-
if ( Logger.isDebugEnabled ) {
194-
Logger.debug("[securesocial] trying sign up with token %s".format(token))
195-
}
194+
logger.debug("[securesocial] trying sign up with token %s".format(token))
196195
executeForToken(token, true, { _ =>
197196
Ok(use[TemplatesPlugin].getSignUpPage(form, token))
198197
})
@@ -220,9 +219,7 @@ object Registration extends Controller {
220219
executeForToken(token, true, { t =>
221220
form.bindFromRequest.fold (
222221
errors => {
223-
if ( Logger.isDebugEnabled ) {
224-
Logger.debug("[securesocial] errors " + errors)
225-
}
222+
logger.debug("[securesocial] errors " + errors)
226223
BadRequest(use[TemplatesPlugin].getSignUpPage(errors, t.uuid))
227224
},
228225
info => {
@@ -302,7 +299,7 @@ object Registration extends Controller {
302299
( Success -> Messages(PasswordUpdated), eventSession)
303300
}
304301
case _ => {
305-
Logger.error("[securesocial] could not find user with email %s during password reset".format(t.email))
302+
logger.error("[securesocial] could not find user with email %s during password reset".format(t.email))
306303
( Error -> Messages(ErrorUpdatingPassword), None)
307304
}
308305
}

module-code/app/securesocial/core/Events.scala

+5-3
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
package securesocial.core
1818

1919
import play.api.mvc.{Controller, Session, RequestHeader}
20-
import play.api.{Logger, Plugin}
20+
import play.api.Plugin
2121

2222
/**
2323
* A trait to model SecureSocial events
@@ -58,14 +58,16 @@ case class PasswordResetEvent(user: Identity) extends Event
5858
* The event listener interface
5959
*/
6060
abstract class EventListener extends Plugin with Registrable with Controller {
61+
private val logger = play.api.Logger("securesocial.core.EventListener")
62+
6163
override def onStart() {
62-
Logger.info("[securesocial] loaded event listener %s".format(id))
64+
logger.info("[securesocial] loaded event listener %s".format(id))
6365
Registry.eventListeners.register(this)
6466
}
6567

6668

6769
override def onStop() {
68-
Logger.info("[securesocial] unloaded event listener %s".format(id))
70+
logger.info("[securesocial] unloaded event listener %s".format(id))
6971
Registry.eventListeners.unRegister(id)
7072
}
7173
/**

module-code/app/securesocial/core/IdentityProvider.scala

+9-6
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ package securesocial.core
1818

1919
import providers.utils.RoutesHelper
2020
import play.api.mvc.{SimpleResult, AnyContent, Request}
21-
import play.api.{Play, Application, Logger, Plugin}
21+
import play.api.{Play, Application, Plugin}
2222
import concurrent.{Await, Future}
2323
import play.api.libs.ws.Response
2424

@@ -29,6 +29,8 @@ import play.api.libs.ws.Response
2929
*
3030
*/
3131
abstract class IdentityProvider(application: Application) extends Plugin with Registrable {
32+
private val logger = IdentityProvider.logger
33+
3234
val SecureSocialKey = "securesocial."
3335
val Dot = "."
3436

@@ -37,15 +39,15 @@ abstract class IdentityProvider(application: Application) extends Plugin with Re
3739
* Registers the provider in the Provider Registry
3840
*/
3941
override def onStart() {
40-
Logger.info("[securesocial] loaded identity provider: %s".format(id))
42+
logger.info("[securesocial] loaded identity provider: %s".format(id))
4143
Registry.providers.register(this)
4244
}
4345

4446
/**
4547
* Unregisters the provider
4648
*/
4749
override def onStop() {
48-
Logger.info("[securesocial] unloaded identity provider: %s".format(id))
50+
logger.info("[securesocial] unloaded identity provider: %s".format(id))
4951
Registry.providers.unRegister(id)
5052
}
5153

@@ -100,7 +102,7 @@ abstract class IdentityProvider(application: Application) extends Plugin with Re
100102
def loadProperty(property: String): Option[String] = {
101103
val result = application.configuration.getString(propertyKey + property)
102104
if ( !result.isDefined ) {
103-
Logger.error("[securesocial] Missing property " + property + " for provider " + id)
105+
logger.error("[securesocial] Missing property " + property + " for provider " + id)
104106
}
105107
result
106108
}
@@ -126,7 +128,7 @@ abstract class IdentityProvider(application: Application) extends Plugin with Re
126128

127129
protected def throwMissingPropertiesException() {
128130
val msg = "[securesocial] Missing properties for provider '%s'. Verify your configuration file is properly set.".format(id)
129-
Logger.error(msg)
131+
logger.error(msg)
130132
throw new RuntimeException(msg)
131133
}
132134

@@ -136,13 +138,14 @@ abstract class IdentityProvider(application: Application) extends Plugin with Re
136138
}
137139

138140
object IdentityProvider {
141+
private val logger = play.api.Logger("securesocial.core.IdentityProvider")
139142
val SessionId = "sid"
140143

141144
val sslEnabled: Boolean = {
142145
import Play.current
143146
val result = current.configuration.getBoolean("securesocial.ssl").getOrElse(false)
144147
if ( !result && Play.isProd ) {
145-
Logger.warn(
148+
logger.warn(
146149
"[securesocial] IMPORTANT: Play is running in production mode but you did not turn SSL on for SecureSocial." +
147150
"Not using SSL can make it really easy for an attacker to steal your users' credentials and/or the " +
148151
"authenticator cookie and gain access to the system."

module-code/app/securesocial/core/OAuth1Provider.scala

+6-6
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ package securesocial.core
1919
import _root_.java.util.UUID
2020
import play.api.cache.Cache
2121
import play.api.libs.oauth.{RequestToken, ConsumerKey, OAuth, ServiceInfo}
22-
import play.api.{Application, Logger, Play}
22+
import play.api.{Application, Play}
2323
import providers.utils.RoutesHelper
2424
import play.api.mvc.{SimpleResult, AnyContent, Request}
2525
import play.api.mvc.Results.Redirect
@@ -30,6 +30,8 @@ import Play.current
3030
* Base class for all OAuth1 providers
3131
*/
3232
abstract class OAuth1Provider(application: Application) extends IdentityProvider(application) {
33+
private val logger = play.api.Logger("securesocial.core.OAuth1Provider")
34+
3335
val serviceInfo = createServiceInfo(propertyKey)
3436
val service = OAuth(serviceInfo, use10a = true)
3537

@@ -77,7 +79,7 @@ abstract class OAuth1Provider(application: Application) extends IdentityProvider
7779
)
7880
)
7981
case Left(oauthException) =>
80-
Logger.error("[securesocial] error retrieving access token", oauthException)
82+
logger.error("[securesocial] error retrieving access token", oauthException)
8183
throw new AuthenticationException()
8284
}
8385
}
@@ -86,9 +88,7 @@ abstract class OAuth1Provider(application: Application) extends IdentityProvider
8688
// the oauth_verifier field is not in the request, this is the 1st step in the auth flow.
8789
// we need to get the request tokens
8890
val callbackUrl = RoutesHelper.authenticate(id).absoluteURL(IdentityProvider.sslEnabled)
89-
if ( Logger.isDebugEnabled ) {
90-
Logger.debug("[securesocial] callback url = " + callbackUrl)
91-
}
91+
logger.debug("[securesocial] callback url = " + callbackUrl)
9292
service.retrieveRequestToken(callbackUrl) match {
9393
case Right(accessToken) =>
9494
val cacheKey = UUID.randomUUID().toString
@@ -97,7 +97,7 @@ abstract class OAuth1Provider(application: Application) extends IdentityProvider
9797
Cache.set(cacheKey, accessToken, 300) // set it for 5 minutes, plenty of time to log in
9898
Left(redirect)
9999
case Left(e) =>
100-
Logger.error("[securesocial] error retrieving request token", e)
100+
logger.error("[securesocial] error retrieving request token", e)
101101
throw new AuthenticationException()
102102
}
103103
}

module-code/app/securesocial/core/OAuth2Provider.scala

+10-13
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ package securesocial.core
1818

1919
import _root_.java.net.URLEncoder
2020
import _root_.java.util.UUID
21-
import play.api.{Logger, Play, Application}
21+
import play.api.{Play, Application}
2222
import play.api.cache.Cache
2323
import Play.current
2424
import play.api.mvc._
@@ -32,6 +32,8 @@ import scala.Some
3232
* Base class for all OAuth2 providers
3333
*/
3434
abstract class OAuth2Provider(application: Application, jsonResponse: Boolean = true) extends IdentityProvider(application) {
35+
private val logger = play.api.Logger("securesocial.core.OAuth2Provider")
36+
3537
val settings = createSettings()
3638

3739
def authMethod = AuthenticationMethod.OAuth2
@@ -73,17 +75,15 @@ abstract class OAuth2Provider(application: Application, jsonResponse: Boolean =
7375
buildInfo(awaitResult(call))
7476
} catch {
7577
case e: Exception => {
76-
Logger.error("[securesocial] error trying to get an access token for provider %s".format(id), e)
78+
logger.error("[securesocial] error trying to get an access token for provider %s".format(id), e)
7779
throw new AuthenticationException()
7880
}
7981
}
8082
}
8183

8284
protected def buildInfo(response: Response): OAuth2Info = {
8385
val json = response.json
84-
if ( Logger.isDebugEnabled ) {
85-
Logger.debug("[securesocial] got json back [" + json + "]")
86-
}
86+
logger.debug("[securesocial] got json back [" + json + "]")
8787
OAuth2Info(
8888
(json \ OAuth2Constants.AccessToken).as[String],
8989
(json \ OAuth2Constants.TokenType).asOpt[String],
@@ -97,7 +97,7 @@ abstract class OAuth2Provider(application: Application, jsonResponse: Boolean =
9797
error match {
9898
case OAuth2Constants.AccessDenied => throw new AccessDeniedException()
9999
case _ =>
100-
Logger.error("[securesocial] error '%s' returned by the authorization server. Provider type is %s".format(error, id))
100+
logger.error("[securesocial] error '%s' returned by the authorization server. Provider type is %s".format(error, id))
101101
throw new AuthenticationException()
102102
}
103103
throw new AuthenticationException()
@@ -119,9 +119,7 @@ abstract class OAuth2Provider(application: Application, jsonResponse: Boolean =
119119
)
120120
SocialUser(IdentityId("", id), "", "", "", None, None, authMethod, oAuth2Info = oauth2Info)
121121
}
122-
if ( Logger.isDebugEnabled ) {
123-
Logger.debug("[securesocial] user = " + user)
124-
}
122+
logger.debug("[securesocial] user = " + user)
125123
user match {
126124
case Some(u) => Right(u)
127125
case _ => throw new AuthenticationException()
@@ -140,10 +138,9 @@ abstract class OAuth2Provider(application: Application, jsonResponse: Boolean =
140138
settings.authorizationUrlParams.foreach( e => { params = e :: params })
141139
val url = settings.authorizationUrl +
142140
params.map( p => URLEncoder.encode(p._1, "UTF-8") + "=" + URLEncoder.encode(p._2, "UTF-8")).mkString("?", "&", "")
143-
if ( Logger.isDebugEnabled ) {
144-
Logger.debug("[securesocial] authorizationUrl = %s".format(settings.authorizationUrl))
145-
Logger.debug("[securesocial] redirecting to: [%s]".format(url))
146-
}
141+
logger.debug("[securesocial] authorizationUrl = %s".format(settings.authorizationUrl))
142+
logger.debug("[securesocial] redirecting to: [%s]".format(url))
143+
147144
Left(Results.Redirect( url ).withSession(request.session + (IdentityProvider.SessionId, sessionId)))
148145
}
149146
}

module-code/app/securesocial/core/Registry.scala

+3-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
*/
1717
package securesocial.core
1818

19-
import play.api.Logger
2019
import providers.UsernamePasswordProvider
2120
import providers.utils.PasswordHasher
2221
import scala.None
@@ -27,6 +26,8 @@ trait Registrable {
2726
}
2827

2928
class PluginRegistry[T <: Registrable](label: String) {
29+
private val logger = play.api.Logger("securesocial.core.PluginRegistry")
30+
3031
private var registry = Map[String, T]()
3132

3233
def register(plugin: T) {
@@ -43,7 +44,7 @@ class PluginRegistry[T <: Registrable](label: String) {
4344
}
4445

4546
def get(id: String): Option[T] = registry.get(id) orElse {
46-
Logger.error("[securesocial] can't find %s for id %s".format(label, id))
47+
logger.error("[securesocial] can't find %s for id %s".format(label, id))
4748
None
4849
}
4950

0 commit comments

Comments
 (0)