Skip to content

Commit c0d6b51

Browse files
authored
Merge pull request #7 from jpbnetley/feature/logging
Feature/logging
2 parents 174188d + 5d477f5 commit c0d6b51

File tree

8 files changed

+63
-15
lines changed

8 files changed

+63
-15
lines changed

build.sbt

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ name := "Mongo-csv-importer"
33
version := "0.1"
44

55
libraryDependencies ++= Seq(
6-
"org.mongodb.scala" %% "mongo-scala-driver" % "2.8.0",
7-
"io.monix" %% "monix" % "3.1.0",
8-
"org.typelevel" %% "cats-core" % "2.1.0"
6+
"org.mongodb.scala" %% "mongo-scala-driver" % "2.8.0",
7+
"io.monix" %% "monix" % "3.1.0",
8+
"org.typelevel" %% "cats-core" % "2.1.0",
9+
"ch.qos.logback" % "logback-classic" % "1.2.3",
10+
"com.typesafe.scala-logging" %% "scala-logging" % "3.9.2"
911
)
1012

1113
scalaVersion := "2.13.1"

src/main/resources/logback.xml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<configuration>
2+
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
3+
<layout class="ch.qos.logback.classic.PatternLayout">
4+
<pattern>%d %green([%thread]) %highlight(%level) %logger{50} - %msg%n</pattern>
5+
</layout>
6+
</appender>
7+
<logger name="com.base22" level="TRACE"/>
8+
<root level="error">
9+
<appender-ref ref="STDOUT"/>
10+
</root>
11+
</configuration>

src/main/scala/Util/DataBuilder/DataBuilder.scala

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package Util.DataBuilder
22
import org.bson.Document
33
import cats.implicits._
44
import monix.eval.Task
5+
import Util.Logging.log
56

67

78
object DataBuilder {
@@ -13,17 +14,19 @@ object DataBuilder {
1314
* @return bsonDocument as String
1415
*/
1516
def buildMongoDocuments(headers: Option[List[String]], lineItems: List[String]): Task[Either[Exception, List[Document]]] = Task {
17+
log.debug("finding headers")
1618
val header = Either.fromOption(headers, new Exception("No Headers found for csv"))
1719
header.map(headers => buildJsonObject(headers, lineItems))
1820
}
1921

2022
/** Checks of the line items are the same length as the headers, otherwise adds NULL for the missing headers
2123
*
2224
* @param lineRow the single line item that is comma separated (csv)
23-
* @param maxIndex
25+
* @param maxIndex the max index for the line items
2426
* @return Csv with null for empty items
2527
*/
2628
def handleShortColumnHeader(lineRow: String, maxIndex: Int): List[String] = {
29+
@scala.annotation.tailrec
2730
def loopOverCsvString(acc: List[String], currentIndex: Int, maxIndex: Int): List[String] = {
2831
if(currentIndex == maxIndex)
2932
acc
@@ -53,7 +56,7 @@ object DataBuilder {
5356

5457
/** Parses json with no Nulls
5558
*
56-
* @param currentIndex
59+
* @param currentIndex position of the parser
5760
* @param headerText for each object
5861
* @param item value for the header text
5962
* @param maxIndex max length of the csv file
@@ -79,7 +82,7 @@ object DataBuilder {
7982

8083
/** Parses json with that contains a Null
8184
*
82-
* @param currentIndex
85+
* @param currentIndex value for the parser
8386
* @param headerText for each object
8487
* @param item value for the header text
8588
* @param maxIndex max length of the csv file
@@ -105,6 +108,7 @@ object DataBuilder {
105108
* @return List[Document]
106109
*/
107110
def buildJsonObject(headerValue: List[String], lineItems: List[String]): List[Document] = {
111+
log.debug("Parsing json")
108112
val maxHeaderIndex = headerValue.length - 1
109113
val jsonObjects = lineItems.map { line =>
110114
val nonEmptyCsvLine = handleShortColumnHeader(line, maxHeaderIndex)

src/main/scala/Util/DataBuilder/Processing.scala

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import org.bson.Document
1111
import scala.concurrent.Await
1212
import scala.concurrent.duration.Duration
1313
import scala.reflect.io.File
14+
import Util.Logging.log
1415

1516
object Processing {
1617

@@ -30,7 +31,7 @@ object Processing {
3031
lineItems = fileLines.drop(1)
3132
collectionName = file.name.replace(".csv", "").toLowerCase
3233
documentResult <- EitherT(buildMongoDocuments(headers, lineItems))
33-
db <- EitherT.right[Exception](database.getDatabase())
34+
db <- EitherT.right[Exception](database.getDatabase)
3435
dbInsert <- EitherT.rightT[Task, Exception](db.getCollection[Document](collectionName).insertMany(documentResult))
3536
} yield {
3637
println(s"Inserting into db: $dbInsert")
@@ -39,6 +40,7 @@ object Processing {
3940
}).value
4041
}.map { result =>
4142
val (errors, _) = result.separate
43+
log.error(errors.headOption.fold("No error found")(_.getMessage))
4244
errors.headOption.toLeft(())
4345
}
4446
}

src/main/scala/Util/Database/Database.scala

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,7 @@ case object Database {
6262
*
6363
* @return
6464
*/
65-
def getDatabase: Task[MongoDatabase] = Task {
66-
database
67-
}
65+
def getDatabase: Task[MongoDatabase] = Task(database)
6866

6967
/** Closes the mongo connection
7068
*

src/main/scala/Util/File/FileHelper.scala

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import monix.eval.Task
66

77
import scala.io.Source
88
import scala.reflect.io.{Directory, File, Path}
9+
import Util.Logging.log
910

1011
object FileHelper {
1112
/** Gets csv files
@@ -15,11 +16,13 @@ object FileHelper {
1516
* @return
1617
*/
1718
def getCsvFiles(dir: Directory, skipFiles: List[File] = List.empty[File]): Task[Either[Exception, List[File]]] = {
19+
log.debug("Skipping files that are not csv items")
1820
Task {
1921
val okFileExtensions = List("csv")
2022
Right(dir.files.filter(file => okFileExtensions.contains(file.extension)).toList)
2123
}.onErrorHandle { e =>
2224
val message = s"Could not read files from path: ${e.getMessage}"
25+
log.error(message, e)
2326
Left(new Exception(message))
2427
}
2528
}
@@ -30,11 +33,16 @@ object FileHelper {
3033
* @return line items
3134
*/
3235
def extractCsvFileLines(file: File): Task[Either[Exception, List[String]]] = Task{
36+
3337
try {
38+
log.debug("Reading in file")
3439
val reader = Source.fromFile(file.toURI, StandardCharsets.ISO_8859_1.name())
3540
Right(reader.getLines().toList)
3641
} catch {
37-
case e: Exception => Left(new Exception("Failed to extract csv files: "+ e.getMessage, e))
42+
case e: Exception =>
43+
val message = "Failed to extract csv files: "+ e.getMessage
44+
log.error(message)
45+
Left(new Exception(message, e))
3846
}
3947
}
4048

@@ -45,7 +53,12 @@ object FileHelper {
4553
* @return optional found file
4654
*/
4755
def findFile(dir: Directory, fileName: String): Task[Either[Exception, File]] = Task {
48-
Either.fromOption(dir.files.toList.find(_.name == fileName), new Exception("File not found: "+ fileName))
56+
log.debug("Finding file by name")
57+
Either.fromOption(dir.files.toList.find(_.name == fileName), {
58+
val error = new Exception("File not found: " + fileName)
59+
log.error(error.getMessage)
60+
error
61+
})
4962
}
5063

5164
/** Casts a string to a url
@@ -55,10 +68,13 @@ object FileHelper {
5568
*/
5669
def toDirectory(dir: String): Either[Exception, Directory] = {
5770
try{
71+
log.debug("Build directory from path string")
5872
val directory = File(Path(dir))
5973
Right(Directory(directory))
6074
} catch {
61-
case e: Exception => Left(new Exception(s"Could not convert to Directory $dir", e))
75+
case e: Exception =>
76+
val error = new Exception(s"Could not convert to Directory $dir", e)
77+
Left(error)
6278
}
6379
}
6480

src/main/scala/Util/Logging.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package Util
2+
3+
import com.typesafe.scalalogging.Logger
4+
import org.slf4j.LoggerFactory
5+
6+
object Logging {
7+
val log: Logger = Logger(LoggerFactory.getLogger("Mongo csv importer"))
8+
}

src/main/scala/Util/UserPrompt.scala

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import Util.Models.UserInput
55
import cats.data.EitherT
66
import cats.implicits._
77
import monix.eval.Task
8+
import Util.Logging.log
89

910
object UserPrompt {
1011

@@ -14,6 +15,7 @@ object UserPrompt {
1415
*/
1516
def promptUser(): Task[Either[Exception, UserInput]] = {
1617
try {
18+
log.debug("Prompting user for input...")
1719
println("Please enter the path to the csv files: ")
1820
(for {
1921
directory <- EitherT.fromEither[Task](FileHelper.toDirectory(scala.io.StdIn.readLine()))
@@ -28,24 +30,29 @@ object UserPrompt {
2830
} catch {
2931
case e: Exception =>
3032
val message = s"Could not read user input: ${e.getMessage}"
33+
log.error(message)
3134
Task.now(Left(new Exception(message)))
3235
}
3336
}
3437

3538
/** Prompts the user to add files to skip
3639
*
37-
* @param inputItems
40+
* @param inputItems the items that will skipped
3841
* @return skipped items list
3942
*/
4043
def addSkipItems(inputItems: List[String]): Either[Exception, List[String]] = {
4144
try {
45+
log.debug("Prompting user to enter files to skip")
4246
println("Please enter any files to skip (enter :q to exit) eg. filename.extension: ")
4347
val input = scala.io.StdIn.readLine()
4448
if (input.equals(":q"))
4549
Right(inputItems)
4650
else addSkipItems(inputItems :+ input)
4751
} catch {
48-
case e: Exception => Left(new Exception("Could not read user input: "+e.getMessage, e))
52+
case e: Exception =>
53+
val message = "Could not read user input: "+e.getMessage
54+
log.error(message)
55+
Left(new Exception(message, e))
4956
}
5057
}
5158

0 commit comments

Comments
 (0)