Selaa lähdekoodia

[add] 암호화 과정 로그 및 기본적인 로그 추가

master
kidjung 4 vuotta sitten
vanhempi
commit
b5a798a7b4
2 muutettua tiedostoa jossa 93 lisäystä ja 36 poistoa
  1. 40
    0
      src/logConfig.go
  2. 53
    36
      src/main.go

+ 40
- 0
src/logConfig.go Näytä tiedosto

@@ -0,0 +1,40 @@
1
+package main
2
+
3
+import (
4
+	"go.uber.org/zap"
5
+	"go.uber.org/zap/zapcore"
6
+)
7
+
8
+func MyEncoderConfig() zapcore.EncoderConfig {
9
+	return zapcore.EncoderConfig{
10
+		// Keys can be anything except the empty string.
11
+		TimeKey:  "T",
12
+		LevelKey: "L",
13
+		NameKey:  "N",
14
+		//CallerKey:      "C",
15
+		FunctionKey:    zapcore.OmitKey,
16
+		MessageKey:     "M",
17
+		StacktraceKey:  "S",
18
+		LineEnding:     zapcore.DefaultLineEnding,
19
+		EncodeLevel:    zapcore.CapitalColorLevelEncoder,
20
+		EncodeTime:     zapcore.ISO8601TimeEncoder,
21
+		EncodeDuration: zapcore.StringDurationEncoder,
22
+		EncodeCaller:   zapcore.ShortCallerEncoder,
23
+	}
24
+}
25
+
26
+func NewMyLogger() *zap.Logger {
27
+	cfg := zap.Config{
28
+		Level:            zap.NewAtomicLevelAt(zap.DebugLevel),
29
+		Development:      true,
30
+		Encoding:         "console",
31
+		EncoderConfig:    MyEncoderConfig(),
32
+		OutputPaths:      []string{"stdout", "./test.log"},
33
+		ErrorOutputPaths: []string{"stderr"},
34
+	}
35
+	logger, err := cfg.Build()
36
+	if err != nil {
37
+		panic(err)
38
+	}
39
+	return logger
40
+}

+ 53
- 36
src/main.go Näytä tiedosto

@@ -7,7 +7,6 @@ import (
7 7
 	"encoding/json"
8 8
 	"errors"
9 9
 	"fmt"
10
-	"github.com/fatih/color"
11 10
 	"log"
12 11
 	"math/rand"
13 12
 	"net"
@@ -165,6 +164,9 @@ func (receiver Receiver) Receive(args Args, reply *Reply) error {
165 164
 }
166 165
 
167 166
 func (microService MicroService) Receive(msg MsgUnit) {
167
+	logger := NewMyLogger()
168
+	logger.Sync()
169
+
168 170
 	var msg_type = msg.CheckType()
169 171
 	//메세지 타입에 따라 다르게 처리
170 172
 	switch msg_type {
@@ -181,7 +183,7 @@ func (microService MicroService) Receive(msg MsgUnit) {
181 183
 	case RM: //Register msg
182 184
 
183 185
 		microService.IsConnected <- true
184
-		log.Println("you received RM: Registered Complete!")
186
+		logger.Info("MM Registered this node Complete!")
185 187
 
186 188
 	case WM: //Withdraw msg
187 189
 		//moscato.MicroServiceManager.RemoveMicroservice(msg.(*WithdrawMsg).From)
@@ -316,6 +318,8 @@ func generateRanUint64() uint64 {
316 318
 }
317 319
 
318 320
 func main() {
321
+	logger := NewMyLogger()
322
+	logger.Sync()
319 323
 
320 324
 	var argu string
321 325
 	for _, v := range os.Args {
@@ -326,7 +330,7 @@ func main() {
326 330
 	}
327 331
 	MMAddress := argu
328 332
 	if argu == "" {
329
-		println("there is no Message Middleware address")
333
+		logger.Fatal("there is no Message Middleware address")
330 334
 		return
331 335
 	}
332 336
 
@@ -341,8 +345,8 @@ func main() {
341 345
 	microService := MicroService{currentIP, privateKey, shareKey, make(chan bool), MMAddress}
342 346
 	receiver := Receiver{thisNodeAddr: currentIP, microService: microService}
343 347
 
344
-	color.Blue("<current machine address : " + currentIP + "> <MM address : " + MMAddress + ">")
345
-	color.Blue("<private key : " + strconv.FormatUint(uint64(privateKey), 10) + ">")
348
+	logger.Info("current machine address : " + currentIP + " / MM address : " + MMAddress)
349
+	logger.Debug("private key : " + strconv.FormatUint(uint64(privateKey), 10))
346 350
 
347 351
 	errReg := rpc.Register(receiver)
348 352
 	if errReg != nil {
@@ -352,7 +356,7 @@ func main() {
352 356
 
353 357
 	client, err := rpc.Dial("tcp", microService.MMAddress+":8160") // RPC 서버에 연결
354 358
 	if err != nil {
355
-		fmt.Println(err)
359
+		logger.Fatal(err.Error())
356 360
 		return
357 361
 	}
358 362
 	defer client.Close() // main 함수가 끝나기 직전에 RPC 연결을 닫음
@@ -366,24 +370,40 @@ func main() {
366 370
 	args.JsonMsg = RJsonMsg
367 371
 	args.Kind = RM
368 372
 	err = client.Call("Receiver.MmReceive", args, reply)
369
-	log.Println("RM sent!")
373
+	logger.Info("RM sent")
370 374
 	if err != nil {
371 375
 		fmt.Println(err)
372 376
 		return
373 377
 	}
374
-	color.Yellow("MM: " + reply.CompleteLog)
378
+	logger.Debug("[MM] " + reply.CompleteLog)
379
+
380
+	sigs := make(chan os.Signal, 1)
381
+	done := make(chan bool, 1)
382
+
383
+	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
384
+
385
+	go func() {
386
+		sig := <-sigs
387
+		withDraw(message, client)
388
+		//fmt.Println(sig)
389
+		_ = sig
390
+		done <- true
391
+		fmt.Println("\nquit Moscato Successful and terminate microservice")
392
+		os.Exit(0)
393
+	}()
375 394
 
376 395
 	// 연결 되면 채널로 연결 확인이 되어야 다음 단계로 넘어감
377 396
 	checkConnect := <-microService.IsConnected
378 397
 	_ = checkConnect
379 398
 	fmt.Scanln()
380
-	fmt.Println("***** sending Subscription messages *****")
399
+	logger.Info("sending Subscription messages")
381 400
 
382 401
 	/*
383 402
 		파일에서 subscription 읽어서 subscription 보내기
384 403
 		 **/
385 404
 	subFile, err := os.Open("subscription.txt")
386 405
 	if err != nil {
406
+		fmt.Println("sub")
387 407
 		log.Fatalf("Error when opening file: %s", err)
388 408
 	}
389 409
 	defer subFile.Close()
@@ -405,11 +425,16 @@ func main() {
405 425
 			println(numSub, "subscription isAlpha type error.")
406 426
 		}
407 427
 
428
+		numSub++
408 429
 		message = Message{From: microService.ClientAddr, Version: "1", Time: "1", Kind: SM}
409 430
 		subMsg := CreateSubMsg(message, subTopic, subValue, subOperator, subIsAlpha)
431
+		logger.Debug("subMsg #" + strconv.Itoa(numSub) + " topic: " + subTopic + " / value: " + subValue + " / operator: " + subOperator)
432
+		logger.Debug("before enc subMsg #" + strconv.Itoa(numSub) + " topic: " + IntSlice2String(subMsg.Topic))
433
+
410 434
 		//subMsg := CreateSubMsg(message, "soccer", "player", "==", true)
411 435
 		//fmt.Println(pubMsg)
412 436
 		subMsg = EncryptionSubMsg(subMsg, microService.ShareKey, microService.PrivateKey)
437
+		logger.Debug("after enc subMsg #" + strconv.Itoa(numSub) + " topic: " + IntSlice2String(subMsg.Topic))
413 438
 		jsonMsg, _ := subMsg.ConvertToJson()
414 439
 		args.JsonMsg = jsonMsg
415 440
 		args.Kind = subMsg.Kind
@@ -417,18 +442,19 @@ func main() {
417 442
 
418 443
 		//fmt.Println(string(args.JsonMsg))
419 444
 		err = client.Call("Receiver.MmReceive", args, reply)
420
-		log.Println("SM sent! #:", numSub)
445
+		logger.Info("SM sent! #" + strconv.Itoa(numSub))
446
+
421 447
 		if err != nil {
422 448
 			fmt.Println(err)
423 449
 			return
424 450
 		}
425 451
 		//log.Println(reply.CompleteLog)
426
-		color.Yellow("MM: " + reply.CompleteLog)
452
+		logger.Debug("[MM] " + reply.CompleteLog)
427 453
 
428 454
 	}
429 455
 
430 456
 	fmt.Scanln()
431
-	fmt.Println("***** sending Publish messages *****")
457
+	logger.Info("sending Publish messages")
432 458
 
433 459
 	pubFile, err := os.Open("publish.txt")
434 460
 	if err != nil {
@@ -446,11 +472,15 @@ func main() {
446 472
 		pubValue := publishTextSlice[1]
447 473
 		pubContent := publishTextSlice[2]
448 474
 
475
+		numPub++
449 476
 		message = Message{From: microService.ClientAddr, Version: "1", Time: "1", Kind: PM}
450 477
 		pubMsg := CreatePubMsg(message, pubTopic, pubValue, pubContent)
478
+		logger.Debug("pubMsg #" + strconv.Itoa(numSub) + " topic: " + pubTopic + " / value: " + pubValue + " / content: " + pubContent)
479
+		logger.Debug("before enc pubMsg #" + strconv.Itoa(numPub) + " topic: " + IntSlice2String(pubMsg.Topic))
451 480
 		//subMsg := CreateSubMsg(message, "soccer", "player", "==", true)
452 481
 		//fmt.Println("Pub.txt",pubMsg)
453 482
 		pubMsg = EncryptionPubMsg(pubMsg, microService.ShareKey, microService.PrivateKey)
483
+		logger.Debug("after enc pubMsg #" + strconv.Itoa(numPub) + " topic: " + IntSlice2String(pubMsg.Topic))
454 484
 		jsonMsg, _ := pubMsg.ConvertToJson()
455 485
 		args.JsonMsg = jsonMsg
456 486
 		args.Kind = pubMsg.Kind
@@ -458,30 +488,16 @@ func main() {
458 488
 
459 489
 		//fmt.Println(string(args.JsonMsg))
460 490
 		err = client.Call("Receiver.MmReceive", args, reply)
461
-		log.Println("PM sent! #:", numPub)
491
+		logger.Info("PM sent! #" + strconv.Itoa(numSub))
462 492
 		if err != nil {
463 493
 			fmt.Println(err)
464 494
 			return
465 495
 		}
466 496
 		//log.Println(reply.CompleteLog)
467
-		color.Yellow("MM: " + reply.CompleteLog)
497
+		logger.Debug("[MM]: " + reply.CompleteLog)
468 498
 
469 499
 	}
470 500
 
471
-	sigs := make(chan os.Signal, 1)
472
-	done := make(chan bool, 1)
473
-
474
-	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
475
-
476
-	go func() {
477
-		sig := <-sigs
478
-		withDraw(message, client)
479
-		//fmt.Println(sig)
480
-		_ = sig
481
-		done <- true
482
-		fmt.Println("\nquit Moscato Successful and terminate microservice")
483
-	}()
484
-
485 501
 	<-done
486 502
 	return
487 503
 }
@@ -547,14 +563,6 @@ func DecryptionMsg(msg PublishMsg, gyKey int64, privateKey int64) {
547 563
 	} else {
548 564
 		fmt.Println("Value is:", string(runeArr))
549 565
 	}
550
-	//if unicode.IsDigit(runeArr[0]){
551
-	//	fmt.Println("Value is: " + string(runeArr))
552
-	//} else {
553
-	//	//for index := 0; index < len(intArr); index++ {
554
-	//	//	//toPubMsg.Value = append(toPubMsg.Value, int64(intArr[index]))
555
-	//	//	valueInt = append(valueInt, int64(intArr[index]))
556
-	//	//}
557
-	//}
558 566
 
559 567
 	runeArr = nil
560 568
 
@@ -578,3 +586,12 @@ func Listen() {
578 586
 		go rpc.ServeConn(conn)
579 587
 	}
580 588
 }
589
+
590
+func IntSlice2String(target []int64) string {
591
+	var targetString string
592
+	targetString = ""
593
+	for _, value := range target {
594
+		targetString += strconv.FormatInt(int64(value), 10) + " "
595
+	}
596
+	return targetString
597
+}

Loading…
Peruuta
Tallenna