本文整理汇总了Scala中play.api.Logger类的典型用法代码示例。如果您正苦于以下问题:Scala Logger类的具体用法?Scala Logger怎么用?Scala Logger使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Logger类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ApplicationTimer
//设置package包名称以及导入依赖的类
package services
import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future
@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {
// This code is called when the application starts.
private val start: Instant = clock.instant
Logger.info(s"ApplicationTimer demo: Starting application at $start.")
// When the application starts, register a stop hook with the
// ApplicationLifecycle object. The code inside the stop hook will
// be run when the application stops.
appLifecycle.addStopHook { () =>
val stop: Instant = clock.instant
val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
Future.successful(())
}
}
示例2: injectorModules
//设置package包名称以及导入依赖的类
package global
import actors.ChadashSystem
import com.google.inject.{Guice, Module}
import play.api.mvc.{EssentialAction, Filters}
import play.api.{Application, GlobalSettings, Logger, Mode}
import play.filters.gzip.GzipFilter
import play.filters.headers.SecurityHeadersFilter
trait AppGlobalSettings extends GlobalSettings {
private var INJECTOR: Option[com.google.inject.Injector] = None
def injectorModules(): Seq[Module]
override def onStart(app: Application) {
INJECTOR = Some(Guice.createInjector(injectorModules(): _*))
}
override def onStop(app: Application) {
Logger.info("Application shutdown...")
if(app.mode != Mode.Test)
ChadashSystem.system.shutdown()
}
override def doFilter(next: EssentialAction): EssentialAction = {
Filters(super.doFilter(next), new GzipFilter(), SecurityHeadersFilter())
}
override def getControllerInstance[A](controllerClass: Class[A]): A = {
INJECTOR match {
case Some(x) => x.getInstance(controllerClass)
case None => throw new UnsupportedOperationException("The DI framework has not been setup yet!")
}
}
}
示例3: FilmController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import models.film.{Film, FilmRepository, Isbn}
import play.api.Logger
import play.api.libs.json._
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
class FilmController @Inject()(filmRepository: FilmRepository)(implicit exec: ExecutionContext) extends Controller {
def createFilm = Action.async(parse.json) { implicit request =>
request.body.validate[Film].map { film =>
Logger.debug(s"Creating film using isbn: ${film.isbn}")
filmRepository.create(film)
.map { f =>
Logger.info("Successfully created a film")
Created(Json.toJson(f))
}
.recover {
case e: Throwable =>
Logger.error("Error creating film", e)
InternalServerError(Json.obj("error" -> "Error creating film"))
}
}.recoverTotal { e =>
Logger.warn(s"Unable to create a film: ${JsError.toJson(e)}")
Future.successful(BadRequest(Json.obj("error" -> s"unable to create film. Cause ${e}")))
}
}
def findFilmBy(isbn: Isbn) = Action.async { implicit request =>
filmRepository.get(isbn).map { maybeFilm =>
maybeFilm.fold(NotFound(Json.obj("error" -> s"${isbn.value} not found")))(f => Ok(Json.toJson(f)))
}.recover {
case e: Throwable =>
Logger.error(s"Error finding film using isbn: $isbn", e)
InternalServerError(Json.obj("error" -> "Error finding films"))
}
}
}
示例4: onServerError
//设置package包名称以及导入依赖的类
package org.danielnixon.progressive.play
import play.api.Logger
import play.api.http.HttpErrorHandler
import play.api.http.HttpVerbs.{ GET, POST }
import play.api.http.Status.INTERNAL_SERVER_ERROR
import play.api.mvc.Results._
import play.api.mvc.{ Call, RequestHeader, Result }
import org.danielnixon.progressive.play.extensions.{ RequestHeaderWrapper, ResultWrapper }
import org.danielnixon.progressive.play.Results.redirectToRefererOrElse
import org.danielnixon.progressive.shared.api.AjaxResponse
import play.twirl.api.HtmlFormat
import scalaz.Scalaz._
import scala.concurrent.Future
def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
val errorMessage = serverErrorToErrorMessage(request, exception)
Logger.error(errorMessage, exception)
errorResponse(request, errorMessage, INTERNAL_SERVER_ERROR)
}
private def errorResponse(request: RequestHeader, errorMessage: String, statusCode: Int): Future[Result] = {
val status = Status(statusCode)
Future.successful {
request.isAjax match {
case true => status(AjaxResponse.asJson(AjaxResponse(Some(errorMessage), None, None)))
case false if request.method === POST => redirectToRefererOrElse(errorRoute)(request).flashingError(errorMessage)
case _ => status(errorPage(request, statusCode, errorMessage))
}
}
}
}
示例5: ArtistController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import model.Artist
import play.api.mvc._
import play.api.libs.json.Json
import services.{ArtistServices}
import play.api.Logger
@Singleton
class ArtistController @Inject() (service : ArtistServices) extends Controller {
def getArtist(name: String) = Action {
val response = service.findAllByType(name)
Logger.debug("Attempting risky calculation.")
Ok(Json.toJson(response))
}
def addArtist = Action { request =>
val json = request.body.asJson.get
val stock = Json.fromJson[Artist](json)
println(stock)
stock.isSuccess match {
case true => {
service.add(stock.get);
Ok("The Artist has been added !!!")
}
case _ => Ok("The Artist Didnt get Added!!")
}
}
}
示例6: ApplicationTimer
//设置package包名称以及导入依赖的类
package services
import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future
@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {
// This code is called when the application starts.
private val start: Instant = clock.instant
Logger.info(s"ApplicationTimer demo: Starting application at $start.")
// When the application starts, register a stop hook with the
// ApplicationLifecycle object. The code inside the stop hook wil
// be run when the application stops.
appLifecycle.addStopHook { () =>
val stop: Instant = clock.instant
val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
Future.successful(())
}
}
示例7: stringPersister
//设置package包名称以及导入依赖的类
package services
import javax.inject.{Inject, Singleton}
import akka.NotUsed
import akka.stream._
import akka.stream.scaladsl.{Broadcast, Flow, GraphDSL, Sink}
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits._
import scala.concurrent.Future
import scala.util.{Failure, Success}
def stringPersister(pf: String => Future[Unit]): Flow[String, String, NotUsed] =
Flow.fromGraph(GraphDSL.create() { implicit builder =>
import GraphDSL.Implicits._
val persistenceSink = Sink.foreach[String] { content =>
val f = pf(content)
f.onComplete {
case Success(u) => Logger.debug(s"Persisted content: '$content'")
case Failure(t) => Logger.error(s"Failed to persist content: '$content", t)
}
}
val bcast = builder.add(Broadcast[String](2))
bcast.out(1) ~> persistenceSink
FlowShape(bcast.in, bcast.out(0))
})
}
示例8: Schema
//设置package包名称以及导入依赖的类
package services.database
import jdub.async.Database
import models.queries.ddl._
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import scala.concurrent.Future
object Schema {
val tables = Seq(
"users" -> CreateUsersTable,
"user_profiles" -> CreateUserProfilesTable,
"password_info" -> CreatePasswordInfoTable,
"oauth1_info" -> CreateOAuth1InfoTable,
"oauth2_info" -> CreateOAuth2InfoTable,
"openid_info" -> CreateOpenIdInfoTable,
"session_info" -> CreateSessionInfoTable
)
def update() = {
Future.sequence(tables.map { t =>
Database.query(DdlQueries.DoesTableExist(t._1)).flatMap { exists =>
if (exists) {
Future.successful(Unit)
} else {
Logger.info(s"Creating missing table [${t._1}].")
val name = s"CreateTable-${t._1}"
Database.raw(name, t._2.sql).map(x => Unit)
}
}
})
}
}
示例9: PlaceController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import models._
import play.api.Logger
import play.api.libs.json._
import play.api.mvc._
import play.modules.reactivemongo._
import reactivemongo.api.ReadPreference
import reactivemongo.play.json.collection._
import utils.Errors
import play.modules.reactivemongo.json._
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class PlaceController @Inject()(val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext) extends Controller with MongoController with ReactiveMongoComponents {
def placeFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("place"))
def create(name: String, location: Location, residents: Seq[Resident] ) = Action.async {
for {
places <- placeFuture
lastError <- places.insert(Place(name, location, residents))
} yield
Ok("Mongo LastError: %s".format(lastError))
}
def createFromJson = Action.async(parse.json) { request =>
Json.fromJson[Place](request.body) match {
case JsSuccess(place, _) =>
for {
places <- placeFuture
lastError <- places.insert(place)
} yield {
Logger.debug(s"Successfully inserted with LastError: $lastError")
Created("Created 1 place")
}
case JsError(errors) =>
Future.successful(BadRequest("Could not build a place from the json provided. " + Errors.show(errors)))
}
}
def findPlace(name: String) = Action.async {
val futurePlacesList: Future[List[Place]] = placeFuture.flatMap{
_.find(Json.obj("name" -> name)).
cursor[Place](ReadPreference.primary).
collect[List]()
}
futurePlacesList.map { places =>
Ok(Json.prettyPrint(Json.toJson(places))) }
}
}
示例10: LocationController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
//import models.City
import play.api.Logger
import play.api.libs.json._
import play.api.mvc._
import play.modules.reactivemongo._
import reactivemongo.play.json.collection._
import utils.Errors
import models._
import scala.concurrent.{ExecutionContext, Future}
import play.modules.reactivemongo.json._
@Singleton
class LocationController @Inject()(val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext) extends Controller with MongoController with ReactiveMongoComponents {
def locationFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("location"))
def create(lat: Double, long: Double) = Action.async {
for {
locations <- locationFuture
lastError <- locations.insert(Location(lat, long))
} yield
Ok("Mongo LastError: %s".format(lastError))
}
def createFromJson = Action.async(parse.json) { request =>
Json.fromJson[Location](request.body) match {
case JsSuccess(location, _) =>
for {
locations <- locationFuture
lastError <- locations.insert(location)
} yield {
Logger.debug(s"Successfully inserted with LastError: $lastError")
Created("Created 1 location")
}
case JsError(errors) =>
Future.successful(BadRequest("Could not build a location from the json provided. " + Errors.show(errors)))
}
}
}
示例11: Forms
//设置package包名称以及导入依赖的类
package Forms
import java.util
import Models.Room
import play.api.Logger
import play.api.data._
import play.api.data.Forms._
import scala.collection.JavaConversions._
object Forms {
case class RoomFull(name:String,number:Int,cost:BigDecimal,items:Option[String]){
def getRoom = {
val room = Room(name,number,cost)
this.items match {
case Some(x) =>var arr = new util.ArrayList[String]()
arr.appendAll(x.split(",").map(_.trim))
// Logger.info(arr.toString)
room.items = arr
// Logger.info(room.items.toString)
case _ =>
}
// Logger.info(room.toString)
room
}
}
val editForm = Form(
mapping(
"name" -> text,
"number" -> number,
"cost" -> bigDecimal,
"items" -> optional(text)
)(RoomFull.apply)(RoomFull.unapply)
)
}
示例12:
//设置package包名称以及导入依赖的类
package actors
import akka.actor._
import play.api.Logger
import shared.ChatTypes.{Channel, User}
import shared._
case CLoginRequest(requestedUsername) =>
allUsers.get(requestedUsername) match {
case None =>
//we escape the name from html related characters
val saveName = Utils.escape(requestedUsername)
allUsers += User(saveName) -> sender
sender ! SLoginSuccessFul(saveName)
case Some(x) =>
sender ! SLoginFailed("Username taken")
}
case [email protected](channelName, partner) =>
ifLoggedIn(user => {
allUsers.get(partner) match {
case Some(ref) => ref ! SInviteToRoom(channelName)
case None => sender ! SNotAuthorized(s"# Can't create custom room with '$partner' for the following reason: User is not logged in!")
}
})
case [email protected]() =>
ifLoggedIn(user => {
for ((name, ref) <- allChannels){
ref forward AuthedMessage(user, m)
}
})
case [email protected](channelName, potMod) =>
ifLoggedIn(user => {
if(user.toString == potMod.toString)
sender ! SNotAuthorized("You can't give or remove moderator rights for yourself")
else
allUsers.get(potMod) match {
case Some(_) => forwardOrCreateChannel(channelName, user, m)
case None => sender ! SNotAuthorized(s"The user $potMod can't be given moderator rights as he's not online")
}
})
case m:AuthedRequiredMessage =>
ifLoggedIn(user => {
forwardOrCreateChannel(m.channelName, user, m)
})
case _ => Logger.warn("Unknown packet in MainServerActor")
}
}
示例13: Application
//设置package包名称以及导入依赖的类
package controllers
import actors.{ServerConnectionActor, ServerActor}
import javax.inject._
import com.google.inject.Inject
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc._
import play.api.libs.iteratee._
import play.api.Logger
import akka.actor._
import scala.concurrent.Future
import scala.util.{Success, Failure}
import shared._
import prickle._
@Singleton
class Application @Inject()(system: ActorSystem) extends Controller {
implicit val messagePickler = ChatPickler.messagePickler
//here we create a connection between the webSocket and the serverConnectionActor
val (out, channel) = Concurrent.broadcast[String]
val connectionHandler = system.actorOf(ServerConnectionActor.props(channel, serverActor))
//for each incoming message try to unpickle it and handle it to the ServerConnectionActor
val in = Iteratee.foreach[String] { msg =>
Unpickle[NetworkMessage].fromString(msg) match {
case Failure(exception) => Logger.error("UNKNOWN PACKET FORMAT")
case Success(value) => connectionHandler ! value
}
}
//return the webSocketHandle
Future(Right(in, out))
}
}
示例14: ProjectRetriever
//设置package包名称以及导入依赖的类
package actors.project
import akka.actor.{Actor, Props}
import messages.ProjectManagerMessages._
import play.api.Logger
class ProjectRetriever extends Actor {
override def receive = {
case GetProjectDetails(projectID) =>
Logger.info(s"actor ${self.path} - received msg : ${GetProjectDetails(projectID)} ")
val projectDetailsRetriever = context.actorOf(ProjectDetailsRetriever.props(sender()), "projectDetailsRetriever")
projectDetailsRetriever forward GetProjectDetails(projectID)
case GetProjectDetailsWithTemplateBody(projectID) =>
Logger.info(s"actor ${self.path} - received msg : ${GetProjectDetailsWithTemplateBody(projectID)} ")
val projectDetailsWithTemplateBodyRetriever = context.actorOf(ProjectDetailsWithTemplateBodyRetriever.props(sender()), "projectDetailsWithTemplateBodyRetriever")
projectDetailsWithTemplateBodyRetriever forward GetProjectDetailsWithTemplateBody(projectID)
case ListProjects(filter, offset, limit) =>
Logger.info(s"actor ${self.path} - received msg : ${ListProjects(filter, offset, limit)} ")
val bulkProjectsRetriever = context.actorOf(BulkProjectsRetriever.props(sender()), "bulkProjectsRetriever")
bulkProjectsRetriever forward ListProjects(filter, offset, limit)
case SearchProjects(keyword, offset, limit) =>
Logger.info(s"actor ${self.path} - received msg : ${SearchProjects(keyword, offset, limit)} ")
val projectsSearchRetriever = context.actorOf(ProjectsSearchRetriever.props(sender()), "projectsSearchRetriever")
projectsSearchRetriever forward SearchProjects(keyword, offset, limit)
case GetProjectStats(projectID) =>
Logger.info(s"actor ${self.path} - received msg : ${GetProjectStats(projectID)} ")
val projectStatsRetriever = context.actorOf(ProjectStatsRetriever.props(sender()), "projectStatsRetriever")
projectStatsRetriever forward GetProjectStats(projectID)
case GetProjectResults(projectID, offset, limit) =>
Logger.info(s"actor ${self.path} - received msg : ${GetProjectResults(projectID, offset, limit)} ")
val projectResultsRetriever = context.actorOf(ProjectResultsRetriever.props(sender()), "projectResultsRetriever")
projectResultsRetriever forward GetProjectResults(projectID, offset, limit)
}
}
object ProjectRetriever {
def props(): Props = Props(new ProjectRetriever)
}
示例15: ApplicationTimer
//设置package包名称以及导入依赖的类
package services
import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future
@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {
// This code is called when the application starts.
private val start: Instant = clock.instant
Logger.info(s"ApplicationTimer demo: Starting application at ${start}.")
// When the application starts, register a stop hook with the
// ApplicationLifecyle object. The code inside the stop hook wil
// be run when the application stops.
appLifecycle.addStopHook { () =>
val stop: Instant = clock.instant
val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
Future.successful(())
}
}