github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/featuretests/cmd_juju_dumplogs_test.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package featuretests 5 6 import ( 7 "bufio" 8 "fmt" 9 "os" 10 "time" 11 12 "github.com/juju/cmd/v3/cmdtesting" 13 "github.com/juju/loggo" 14 jc "github.com/juju/testing/checkers" 15 gc "gopkg.in/check.v1" 16 17 "github.com/juju/juju/agent" 18 "github.com/juju/juju/cmd/jujud/agent/agenttest" 19 "github.com/juju/juju/cmd/jujud/dumplogs" 20 corelogger "github.com/juju/juju/core/logger" 21 "github.com/juju/juju/state" 22 "github.com/juju/juju/testing/factory" 23 "github.com/juju/juju/version" 24 ) 25 26 type dumpLogsCommandSuite struct { 27 agenttest.AgentSuite 28 } 29 30 func (s *dumpLogsCommandSuite) SetUpTest(c *gc.C) { 31 s.AgentSuite.SetUpTest(c) 32 } 33 34 func (s *dumpLogsCommandSuite) TestRun(c *gc.C) { 35 // Create a controller machine and an agent for it. 36 m, password := s.Factory.MakeMachineReturningPassword(c, &factory.MachineParams{ 37 Jobs: []state.MachineJob{state.JobManageModel}, 38 Nonce: agent.BootstrapNonce, 39 }) 40 err := m.SetMongoPassword(password) 41 c.Assert(err, jc.ErrorIsNil) 42 43 s.PrimeStateAgent(c, m.Tag(), password) 44 45 // Create multiple environments and add some logs for each. 46 st1 := s.Factory.MakeModel(c, nil) 47 defer st1.Close() 48 st2 := s.Factory.MakeModel(c, nil) 49 defer st2.Close() 50 states := []*state.State{s.State, st1, st2} 51 52 t := time.Date(2015, 11, 4, 3, 2, 1, 0, time.UTC) 53 for _, st := range states { 54 w := state.NewDbLogger(st) 55 defer w.Close() 56 for i := 0; i < 3; i++ { 57 err := w.Log([]corelogger.LogRecord{{ 58 Time: t, 59 Entity: "machine-42", 60 Version: version.Current, 61 Module: "module", 62 Location: "location", 63 Level: loggo.INFO, 64 Message: fmt.Sprintf("%d", i), 65 Labels: []string{"http"}, 66 }}) 67 c.Assert(err, jc.ErrorIsNil) 68 } 69 } 70 71 // Run the juju-dumplogs command 72 command := dumplogs.NewCommand() 73 context, err := cmdtesting.RunCommand(c, command, "--data-dir", s.DataDir()) 74 c.Assert(err, jc.ErrorIsNil) 75 76 // Check the log file for each environment 77 expectedLog := "machine-42: 2015-11-04 03:02:01 INFO module %d http" 78 for _, st := range states { 79 logName := context.AbsPath(fmt.Sprintf("%s.log", st.ModelUUID())) 80 logFile, err := os.Open(logName) 81 c.Assert(err, jc.ErrorIsNil) 82 scanner := bufio.NewScanner(logFile) 83 for i := 0; scanner.Scan(); i++ { 84 c.Assert(scanner.Text(), gc.Equals, fmt.Sprintf(expectedLog, i)) 85 } 86 c.Assert(scanner.Err(), jc.ErrorIsNil) 87 } 88 }