瀏覽代碼

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

master
kidjung 4 年之前
父節點
當前提交
b5a798a7b4
共有 2 個檔案被更改,包括 93 行新增36 行删除
  1. 40
    0
      src/logConfig.go
  2. 53
    36
      src/main.go

+ 40
- 0
src/logConfig.go 查看文件

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 查看文件

7
 	"encoding/json"
7
 	"encoding/json"
8
 	"errors"
8
 	"errors"
9
 	"fmt"
9
 	"fmt"
10
-	"github.com/fatih/color"
11
 	"log"
10
 	"log"
12
 	"math/rand"
11
 	"math/rand"
13
 	"net"
12
 	"net"
165
 }
164
 }
166
 
165
 
167
 func (microService MicroService) Receive(msg MsgUnit) {
166
 func (microService MicroService) Receive(msg MsgUnit) {
167
+	logger := NewMyLogger()
168
+	logger.Sync()
169
+
168
 	var msg_type = msg.CheckType()
170
 	var msg_type = msg.CheckType()
169
 	//메세지 타입에 따라 다르게 처리
171
 	//메세지 타입에 따라 다르게 처리
170
 	switch msg_type {
172
 	switch msg_type {
181
 	case RM: //Register msg
183
 	case RM: //Register msg
182
 
184
 
183
 		microService.IsConnected <- true
185
 		microService.IsConnected <- true
184
-		log.Println("you received RM: Registered Complete!")
186
+		logger.Info("MM Registered this node Complete!")
185
 
187
 
186
 	case WM: //Withdraw msg
188
 	case WM: //Withdraw msg
187
 		//moscato.MicroServiceManager.RemoveMicroservice(msg.(*WithdrawMsg).From)
189
 		//moscato.MicroServiceManager.RemoveMicroservice(msg.(*WithdrawMsg).From)
316
 }
318
 }
317
 
319
 
318
 func main() {
320
 func main() {
321
+	logger := NewMyLogger()
322
+	logger.Sync()
319
 
323
 
320
 	var argu string
324
 	var argu string
321
 	for _, v := range os.Args {
325
 	for _, v := range os.Args {
326
 	}
330
 	}
327
 	MMAddress := argu
331
 	MMAddress := argu
328
 	if argu == "" {
332
 	if argu == "" {
329
-		println("there is no Message Middleware address")
333
+		logger.Fatal("there is no Message Middleware address")
330
 		return
334
 		return
331
 	}
335
 	}
332
 
336
 
341
 	microService := MicroService{currentIP, privateKey, shareKey, make(chan bool), MMAddress}
345
 	microService := MicroService{currentIP, privateKey, shareKey, make(chan bool), MMAddress}
342
 	receiver := Receiver{thisNodeAddr: currentIP, microService: microService}
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
 	errReg := rpc.Register(receiver)
351
 	errReg := rpc.Register(receiver)
348
 	if errReg != nil {
352
 	if errReg != nil {
352
 
356
 
353
 	client, err := rpc.Dial("tcp", microService.MMAddress+":8160") // RPC 서버에 연결
357
 	client, err := rpc.Dial("tcp", microService.MMAddress+":8160") // RPC 서버에 연결
354
 	if err != nil {
358
 	if err != nil {
355
-		fmt.Println(err)
359
+		logger.Fatal(err.Error())
356
 		return
360
 		return
357
 	}
361
 	}
358
 	defer client.Close() // main 함수가 끝나기 직전에 RPC 연결을 닫음
362
 	defer client.Close() // main 함수가 끝나기 직전에 RPC 연결을 닫음
366
 	args.JsonMsg = RJsonMsg
370
 	args.JsonMsg = RJsonMsg
367
 	args.Kind = RM
371
 	args.Kind = RM
368
 	err = client.Call("Receiver.MmReceive", args, reply)
372
 	err = client.Call("Receiver.MmReceive", args, reply)
369
-	log.Println("RM sent!")
373
+	logger.Info("RM sent")
370
 	if err != nil {
374
 	if err != nil {
371
 		fmt.Println(err)
375
 		fmt.Println(err)
372
 		return
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
 	checkConnect := <-microService.IsConnected
396
 	checkConnect := <-microService.IsConnected
378
 	_ = checkConnect
397
 	_ = checkConnect
379
 	fmt.Scanln()
398
 	fmt.Scanln()
380
-	fmt.Println("***** sending Subscription messages *****")
399
+	logger.Info("sending Subscription messages")
381
 
400
 
382
 	/*
401
 	/*
383
 		파일에서 subscription 읽어서 subscription 보내기
402
 		파일에서 subscription 읽어서 subscription 보내기
384
 		 **/
403
 		 **/
385
 	subFile, err := os.Open("subscription.txt")
404
 	subFile, err := os.Open("subscription.txt")
386
 	if err != nil {
405
 	if err != nil {
406
+		fmt.Println("sub")
387
 		log.Fatalf("Error when opening file: %s", err)
407
 		log.Fatalf("Error when opening file: %s", err)
388
 	}
408
 	}
389
 	defer subFile.Close()
409
 	defer subFile.Close()
405
 			println(numSub, "subscription isAlpha type error.")
425
 			println(numSub, "subscription isAlpha type error.")
406
 		}
426
 		}
407
 
427
 
428
+		numSub++
408
 		message = Message{From: microService.ClientAddr, Version: "1", Time: "1", Kind: SM}
429
 		message = Message{From: microService.ClientAddr, Version: "1", Time: "1", Kind: SM}
409
 		subMsg := CreateSubMsg(message, subTopic, subValue, subOperator, subIsAlpha)
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
 		//subMsg := CreateSubMsg(message, "soccer", "player", "==", true)
434
 		//subMsg := CreateSubMsg(message, "soccer", "player", "==", true)
411
 		//fmt.Println(pubMsg)
435
 		//fmt.Println(pubMsg)
412
 		subMsg = EncryptionSubMsg(subMsg, microService.ShareKey, microService.PrivateKey)
436
 		subMsg = EncryptionSubMsg(subMsg, microService.ShareKey, microService.PrivateKey)
437
+		logger.Debug("after enc subMsg #" + strconv.Itoa(numSub) + " topic: " + IntSlice2String(subMsg.Topic))
413
 		jsonMsg, _ := subMsg.ConvertToJson()
438
 		jsonMsg, _ := subMsg.ConvertToJson()
414
 		args.JsonMsg = jsonMsg
439
 		args.JsonMsg = jsonMsg
415
 		args.Kind = subMsg.Kind
440
 		args.Kind = subMsg.Kind
417
 
442
 
418
 		//fmt.Println(string(args.JsonMsg))
443
 		//fmt.Println(string(args.JsonMsg))
419
 		err = client.Call("Receiver.MmReceive", args, reply)
444
 		err = client.Call("Receiver.MmReceive", args, reply)
420
-		log.Println("SM sent! #:", numSub)
445
+		logger.Info("SM sent! #" + strconv.Itoa(numSub))
446
+
421
 		if err != nil {
447
 		if err != nil {
422
 			fmt.Println(err)
448
 			fmt.Println(err)
423
 			return
449
 			return
424
 		}
450
 		}
425
 		//log.Println(reply.CompleteLog)
451
 		//log.Println(reply.CompleteLog)
426
-		color.Yellow("MM: " + reply.CompleteLog)
452
+		logger.Debug("[MM] " + reply.CompleteLog)
427
 
453
 
428
 	}
454
 	}
429
 
455
 
430
 	fmt.Scanln()
456
 	fmt.Scanln()
431
-	fmt.Println("***** sending Publish messages *****")
457
+	logger.Info("sending Publish messages")
432
 
458
 
433
 	pubFile, err := os.Open("publish.txt")
459
 	pubFile, err := os.Open("publish.txt")
434
 	if err != nil {
460
 	if err != nil {
446
 		pubValue := publishTextSlice[1]
472
 		pubValue := publishTextSlice[1]
447
 		pubContent := publishTextSlice[2]
473
 		pubContent := publishTextSlice[2]
448
 
474
 
475
+		numPub++
449
 		message = Message{From: microService.ClientAddr, Version: "1", Time: "1", Kind: PM}
476
 		message = Message{From: microService.ClientAddr, Version: "1", Time: "1", Kind: PM}
450
 		pubMsg := CreatePubMsg(message, pubTopic, pubValue, pubContent)
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
 		//subMsg := CreateSubMsg(message, "soccer", "player", "==", true)
480
 		//subMsg := CreateSubMsg(message, "soccer", "player", "==", true)
452
 		//fmt.Println("Pub.txt",pubMsg)
481
 		//fmt.Println("Pub.txt",pubMsg)
453
 		pubMsg = EncryptionPubMsg(pubMsg, microService.ShareKey, microService.PrivateKey)
482
 		pubMsg = EncryptionPubMsg(pubMsg, microService.ShareKey, microService.PrivateKey)
483
+		logger.Debug("after enc pubMsg #" + strconv.Itoa(numPub) + " topic: " + IntSlice2String(pubMsg.Topic))
454
 		jsonMsg, _ := pubMsg.ConvertToJson()
484
 		jsonMsg, _ := pubMsg.ConvertToJson()
455
 		args.JsonMsg = jsonMsg
485
 		args.JsonMsg = jsonMsg
456
 		args.Kind = pubMsg.Kind
486
 		args.Kind = pubMsg.Kind
458
 
488
 
459
 		//fmt.Println(string(args.JsonMsg))
489
 		//fmt.Println(string(args.JsonMsg))
460
 		err = client.Call("Receiver.MmReceive", args, reply)
490
 		err = client.Call("Receiver.MmReceive", args, reply)
461
-		log.Println("PM sent! #:", numPub)
491
+		logger.Info("PM sent! #" + strconv.Itoa(numSub))
462
 		if err != nil {
492
 		if err != nil {
463
 			fmt.Println(err)
493
 			fmt.Println(err)
464
 			return
494
 			return
465
 		}
495
 		}
466
 		//log.Println(reply.CompleteLog)
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
 	<-done
501
 	<-done
486
 	return
502
 	return
487
 }
503
 }
547
 	} else {
563
 	} else {
548
 		fmt.Println("Value is:", string(runeArr))
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
 	runeArr = nil
567
 	runeArr = nil
560
 
568
 
578
 		go rpc.ServeConn(conn)
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…
取消
儲存